Answer the question
In order to leave comments, you need to log in
How to get the value of a field in a class using the field name?
There is a model object with a bunch of fields. It is necessary to compare it with another object, but not for all fields, but only for selective ones. How can I find out the value of a field by, for example, the name of the field so that later it can be compared?
Answer the question
In order to leave comments, you need to log in
//has object
Class<? extends Object> clazz = object.getClass();
Field[] fields = clazz.getDeclaredFields();
for(Field field: fields){
String fieldName = field.getName();
if(!field.isAccessible()){
field.setAccessible(true);
}
Object value = field.get(object);
}
Well, somehow through java reflection
// Одно поле
Class c = obj.getClass();
Field nameField = c.getField("name");
// Или все поля
Class c = obj.getClass();
Field[] publicFields = c.getFields();
for (Field field : publicFields) {
Class fieldType = field.getType();
System.out.println("Имя: " + field.getName());
System.out.println("Тип: " + fieldType.getName());
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question