A
A
Alexander Ivanov2014-11-21 11:20:39
Java
Alexander Ivanov, 2014-11-21 11:20:39

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

4 answer(s)
B
brutal_lobster, 2014-11-21
@brutal_lobster

https://docs.oracle.com/javase/tutorial/reflect/me...

D
Dmitry, 2014-11-21
@CTAKAH4uK

//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);
}

A
Alexey Cheremisin, 2014-11-21
@leahch

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()); 
}

Read more here www.quizful.net/post/java-reflection-api for example.

K
Kamerad, 2014-11-22
@kamerad

Class class = instance.getClass();
Field field = class.get("field name");
"field type" value = field.get(instance);
Get the value of the field. In general, it is not clear from the question what is known at the stage of writing the code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question