Если бы у меня была такая строка, которую нужно было преобразовать в объект, я бы создал класс со статическим методом, который возвращает объект Vehicle. Затем вы можете делать все, что хотите, с этим объектом. Несколько геттеров и сеттеров, и вам должно быть хорошо идти.
я пришел с какой-то код, который должен работать, как вы ожидаете, если я понял ваш вопрос :)
Там есть довольно много комментариев, так это должно помочь вам понять логику кода.
Класс автомобиля, где все разборки происходит в статическом методе с именем createVehicle (String keyValueString).
Основной класс:
import java.util.ArrayList;
import java.util.List;
public class main {
public static void main(String[] args) {
String vehicleString = "{id=123, vehicle_name=Tesla Model X, price=80000.00}";
List<Vehicle> vehicles = new ArrayList<Vehicle>();
Vehicle vehicle;
// call the static method passing the string for one vehicle
vehicle = Vehicle.createVehicle(vehicleString);
// if the id is -1, then the default constructor fired since
// there was an error when parsing the code.
if(vehicle.getId() == -1) {
System.out.println("Check your data buddy.");
} else {
vehicles.add(vehicle);
}
for(Vehicle v : vehicles){
System.out.println("Vehicle id: " + v.getId());
System.out.println("Vehicle name: " + v.getVehicle_name());
System.out.println("Vehicle price: " + v.getPrice());
System.out.println();
}
}
}
Транспортное средство Класс:
import java.math.BigDecimal;
public class Vehicle {
// declare your attributes mapped to your string
private int id;
private String vehicle_name;
private BigDecimal price;
// Start Constructor
// Default Constructor
public Vehicle() {
this.setId(-1);
this.setVehicle_name("Empty");
this.setPrice(new BigDecimal(0.00));
}
public Vehicle(int id, String vehicle_name, BigDecimal price) {
this.setId(id);
this.setVehicle_name(vehicle_name);
this.setPrice(price);
}
// End Constructor
// Start Getters and Setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getVehicle_name() {
return vehicle_name;
}
public void setVehicle_name(String vehicle_name) {
this.vehicle_name = vehicle_name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
// End Getters and Setters.
// Start Methods and Functions
// Given a string returns a string array split by a "," and with
// "{}" removed.
private static String[] splitString(String keyValueString) {
String[] split;
// Clean string from unwanted values
keyValueString = keyValueString.replaceAll("[{}]", "");
split = keyValueString.split(",");
return split;
}
// Add a vehicle given a formatted string with key value pairs
public static Vehicle createVehicle(String keyValueString) {
int id = 0;
String vehicle_name = "";
BigDecimal price = null;
String[] split;
Vehicle vehicle;
split = splitString(keyValueString);
// Loop through each keyValue array
for(String keyValueJoined : split){
// split the keyValue again using the "="
String[] keyValue = keyValueJoined.split("=");
// remove white space and add to a String variable
String key = keyValue[0].trim();
String value = keyValue[1].trim();
// check which attribute you currently have and add
// to the appropriate variable
switch(key){
case "id":
id = Integer.parseInt(value);
break;
case "vehicle_name":
vehicle_name = value;
break;
case "price":
try {
price = new BigDecimal(Double.parseDouble(value));
} catch (NumberFormatException e) {
e.printStackTrace();
}
break;
default:
System.out.println("Attribute not available");
return null;
}
}
// if any of the values have not been changed then either the
// data is incomplete or inconsistent so return the default constructor.
// Can be removed or changed if you expected incomplete data. It all
// depends how you would like to handle this.
if(id == 0 || vehicle_name.equals("") || price == null){
vehicle = new Vehicle();
} else {
//System.out.println(id);
vehicle = new Vehicle(id, vehicle_name, price);
}
return vehicle;
}
// End Methods and Functions
}
Программа, с учетом строки при условии, возвращает следующее при обращении вновь созданный объект атрибутов с использованием методов получения:
Номер транспортного средства: 123
Vehi Название НКИ: Tesla Model X
Автомобиля цены: 80000
Надеется, что это помогает.
Соответствующее слово здесь. Есть тонны «подходящих» способов преобразования этого набора атрибутов в объект, начиная с простой «Карты» до фактических экземпляров класса «Car». Вероятно, поле 'id' - это фактически' serialUID' класса, и оно предназначено для десериализации. – Paul
Возможный дубликат [Java parsing string] (http://stackoverflow.com/questions/4822552/java-parsing-string) –
Где вы взяли эту строку? В идеале вы захотите изменить источник данных так, чтобы он выводился в формате, который вы можете легко анализировать. – 4castle