Java,将类的实例转换为 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37024300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java, Convert instance of Class to HashMap
提问by Mr.D
If I have class like this:
如果我有这样的课程:
class MyObject {
public int myInt;
public String myString;
}
Is it possible to convert instance of this class to HashMap without implementing converting code?
是否可以在不实现转换代码的情况下将此类的实例转换为 HashMap?
MyObject obj = new MyObject();
obj.myInt = 1; obj.myString = "string";
HashMap<String, Object> hs = convert(obj);
hs.getInt("myInt"); // returns 1
hs.getString("myString"); // returns "string"
Does Java provide that kind of solution, or I need to implement convert
by myself?
Java 有没有提供那种解决方案,还是需要convert
我自己实现?
My Class has more than 50 fields and writing converter for each field is not so good idea.
我的班级有 50 多个字段,为每个字段编写转换器并不是一个好主意。
采纳答案by PKuhn
You can use reflection for implementing this behavior. You can get all fields of the class you want to convert to map iterate over this fields and take the name of each field as key of the map. This will result in a map from String to object.
您可以使用反射来实现此行为。您可以获取要转换为映射的类的所有字段,遍历这些字段并将每个字段的名称作为映射的键。这将导致从字符串到对象的映射。
Map<String, Object> myObjectAsDict = new HashMap<>();
Field[] allFields = SomeClass.class.getDeclaredFields();
for (Field field : allFields) {
Class<?> targetType = field.getType();
Object objectValue = targetType.newInstance();
Object value = field.get(objectValue);
myObjectAsDict.put(field.getName(), value);
}
}
回答by profcalculus
With Hymanson library this is also possible
使用 Hymanson 库,这也是可能的
MyObject obj = new MyObject();
obj.myInt = 1;
obj.myString = "1";
ObjectMapper mapObject = new ObjectMapper();
Map < String, Object > mapObj = mapObject.convertValue(obj, Map.class);
回答by Mike Murphy
You might consider using a map instead of a class.
您可能会考虑使用地图而不是类。
Or have your class extend a map such as
或者让您的班级扩展地图,例如
public class MyObject extends HashMap<String, Object> {
}
回答by Nicolas Filotto
Something like that will do the trick:
像这样的事情可以解决问题:
MyObject obj = new MyObject();
obj.myInt = 1; obj.myString = "string";
Map<String, Object> map = new HashMap<>();
// Use MyObject.class.getFields() instead of getDeclaredFields()
// If you are interested in public fields only
for (Field field : MyObject.class.getDeclaredFields()) {
// Skip this if you intend to access to public fields only
if (!field.isAccessible()) {
field.setAccessible(true);
}
map.put(field.getName(), field.get(obj));
}
System.out.println(map);
Output:
输出:
{myString=string, myInt=1}
回答by Abdul Mohsin
If you don't want to use Reflection then you can use my trick. hope this may help for someone.
如果你不想使用反射,那么你可以使用我的技巧。希望这可能对某人有所帮助。
Suppose your class looks like this.
假设你的类看起来像这样。
public class MyClass {
private int id;
private String name;
}
Now Override toString() method in this class. in Eclipse there is a shortcut for generating this method also.
现在覆盖这个类中的 toString() 方法。在 Eclipse 中也有一个生成这个方法的快捷方式。
public class MyClass {
private int id;
private String name;
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("MyClass [id=").append(id).append(", name=").append(name).append("]");
return builder.toString();
}
}
Now write a method inside this class that will convert your object into Map<String,String>
现在在这个类中编写一个方法,将您的对象转换为 Map<String,String>
public Map<String, String> asMap() {
Map<String, String> map = new HashMap<String, String>();
String stringRepresentation = this.toString();
if (stringRepresentation == null || stringRepresentation.trim().equals("")) {
return map;
}
if (stringRepresentation.contains("[")) {
int index = stringRepresentation.indexOf("[");
stringRepresentation = stringRepresentation.substring(index + 1, stringRepresentation.length());
}
if (stringRepresentation.endsWith("]")) {
stringRepresentation = stringRepresentation.substring(0, stringRepresentation.length() - 1);
}
String[] commaSeprated = stringRepresentation.split(",");
for (int i = 0; i < commaSeprated.length; i++) {
String keyEqualsValue = commaSeprated[i];
keyEqualsValue = keyEqualsValue.trim();
if (keyEqualsValue.equals("") || !keyEqualsValue.contains("=")) {
continue;
}
String[] keyValue = keyEqualsValue.split("=", 2);
if (keyValue.length > 1) {
map.put(keyValue[0].trim(), keyValue[1].trim());
}
}
return map;
}
Now from any where in your application you can simply call this method to get your HashMap from the Object. Cheers
现在,您可以从应用程序的任何位置简单地调用此方法以从对象中获取 HashMap。干杯