Get properties reflection java

How to get the fields in an Object via reflection?

I have an object (basically a VO) in Java and I don’t know its type.
I need to get values which are not null in that object. How can this be done?

3 Answers 3

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

Object someObject = getItSomehow(); for (Field field : someObject.getClass().getDeclaredFields()) < field.setAccessible(true); // You might want to set modifier to public first. Object value = field.get(someObject); if (value != null) < System.out.println(field.getName() + "=" + value); >> 

To learn more about reflection, check the Oracle tutorial on the subject.

That said, if that VO is a fullworthy Javabean, then the fields do not necessarily represent real properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) < if (Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && method.getReturnType() != void.class && (method.getName().startsWith("get") || method.getName().startsWith("is")) ) < Object value = method.invoke(someObject); if (value != null) < System.out.println(method.getName() + "=" + value); >> > 

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans. There’s even a built-in one provided by Java SE in the java.beans package.

BeanInfo beanInfo = Introspector.getBeanInfo(someObject.getClass()); for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) < Method getter = property.getReadMethod(); if (getter != null) < Object value = getter.invoke(someObject); if (value != null) < System.out.println(property.getName() + "=" + value); >> > 

Источник

Getting value of public static final field/property of a class in Java via reflection

R._1st couldn’t work? If you’re talking about Android development, I think the R class is always there.

@Matthieu I thought so too, until this day when I had to do this very same thing, but only with the BR class.

4 Answers 4

First retrieve the field property of the class, then you can retrieve the value. If you know the type you can use one of the get methods with null (for static fields only, in fact with a static field the argument passed to the get method is ignored entirely). Otherwise you can use getType and write an appropriate switch as below:

Field f = R.class.getField("_1st"); Class t = f.getType(); if(t == int.class)< System.out.println(f.getInt(null)); >else if(t == double.class)< System.out.println(f.getDouble(null)); >. 

thanks. I tried but it didn’t work. Exception is thrown at the operation f.getInt(null). I caught it but how come there’s an exception?

Читайте также:  Java команды lineage 2

How come the documentation never mentions that getInt() ignores the passed in argument? Spent hours on trying to get the instance of the class to pass there.

 R.class.getField("_1st").get(null); 

Exception handling is left as an exercise for the reader.

Basically you get the field like any other via reflection, but when you call the get method you pass in a null since there is no instance to act on.

This works for all static fields, regardless of their being final. If the field is not public, you need to call setAccessible(true) on it first, and of course the SecurityManager has to allow all of this.

Источник

How to get field value using reflection?

Are you sure that a) the fields are actually not null, and b) your program isn’t throwing an exception at the call to field.get ?

How does the returnEntity intialize the returned Object ? It is null probrably because the field is not initialized yet. Getting value of Field.getName() doesn’t mean that the field has value.

Well, if the values are not null, may be you need to set the modifier as accessible by using: field.setAccessible(true); Also, can you paste the stack trace here as well?

it is my mistake, i looked at the code again and it is working. There are lots of null valu in return object and i thought there are a problem. But when i looked all field value, there are some fields is not null. Sorry for wasting your time !

3 Answers 3

I’m guessing, but the name returnEntity suggests that you might be dealing with Hibernate (or JPA) entities or similar.

Those might load their fields only lazily when accesst through getters. If you access them through the fields they still have all null values.

it is my mistake, i looked at the code again and it is working. There are lots of null valu in return object and i thought there are a problem. But when i looked all field value, there are some fields is not null. Sorry for wasting your time !

Читайте также:  Список пользователей

The field might not have been initialized. For ex:

class TestClass < Object o; >public class Test < public static void main(String[] args) < TestClass t = new TestClass(); Class c = t.getClass(); Field f = c.getDeclaredField("o"); Object obj = f.get(t); // will be null >> 

The obj will be null in this case. But if the Object o in TestClass had been initialized, the value of o would not be null :

Object obj = f.get(t); // will not be null 

it is my mistake, i looked at the code again and it is working. There are lots of null valu in return object and i thought there are a problem. But when i looked all field value, there are some fields is not null. Sorry for wasting your time !

one possibility is that you encounter of the byte-code manipulation done by hibernate on the entities. hibernate entities are lazy loaded (by default) . hibernate sticks hooks into the getter/setter methods to load the actual values when you call one of those methods.

You should always use the getters/setters in a hibernate object, not direct field access.

it is my mistake, i looked at the code again and it is working. There are lots of null valu in return object and i thought there are a problem. But when i looked all field value, there are some fields is not null. Sorry for wasting your time !

Источник

Get all fields (even private and inherited) from class

I am making university project.
I need to get all fields from class. Even private and inherited. I tried to get all declared fields and then cast to super class and repeat. Fragment of my code:

private void listAllFields(Object obj) < ListfieldList = new ArrayList(); while (obj != null) < fieldList.addAll(Arrays.asList(obj.getClass().getDeclaredFields())); obj = obj.getClass().getSuperclass().cast(obj); >// rest of code 

But it does not work. tmpObj after casting is still the same class (not superclass).
I will appreciate any help how to fix casting problem, or how to retrieve these fields in different way. Problem is not to gain access to fields, but to get names of fields!
I manages it that way:

private void listAllFields(Object obj) < ListfieldList = new ArrayList(); Class tmpClass = obj.getClass(); while (tmpClass != null) < fieldList.addAll(Arrays.asList(tmpClass .getDeclaredFields())); tmpClass = tmpClass .getSuperclass(); >// rest of code 

9 Answers 9

obj = obj.getClass().getSuperclass().cast(obj); 

This line does not do what you expect it to do. Casting an Object does not actually change it, it just tells the compiler to treat it as something else.

Читайте также:  METANIT.COM

E.g. you can cast a List to a Collection , but it will still remain a List .

However, looping up through the super classes to access fields works fine without casting:

Class current = yourClass; while(current.getSuperclass()!=null) < // we don't want to process Object.class // do something with current's fields current = current.getSuperclass(); >

BTW, if you have access to the Spring Framework, there is a handy method for looping through the fields of a class and all super classes:
ReflectionUtils.doWithFields(baseClass, FieldCallback)
(also see this previous answer of mine: Access to private inherited fields via reflection in Java)

getDeclaredFields() gives you all fields on that Class, including private ones.

getFields() gives you all public fields on that Class AND it’s superclasses.

If you want private / protected methods of Super Classes, you will have to repeatedly call getSuperclass() and then call getDeclaredFields() on the Super Class object.

Nothing here isn’t clearly explained in the javadocs

Here is the method I use to get all the fields of an object

private List getFields(T t) < Listfields = new ArrayList<>(); Class clazz = t.getClass(); while (clazz != Object.class) < fields.addAll(Arrays.asList(clazz.getDeclaredFields())); clazz = clazz.getSuperclass(); >return fields; > 

This solution uses Java 8 streams, useful for those who are learning functional programming in Java. It iterates over getSuperclass and getDeclaredFields as per the other answers, but it does so in a functional way.

The following line will print the name of each field name found on SomeClass or any of its superclasses.

allFieldsFor(SomeClass.class).map(Field::getName).forEach(System.out::println); 

Here is the code that steps through the superclasses to create the stream of fields.

private Stream allFieldsFor( Class c ) < return walkInheritanceTreeFor(c).flatMap( k ->Arrays.stream(k.getDeclaredFields()) ); > private Stream walkInheritanceTreeFor( Class c ) < return iterate( c, k ->Optional.ofNullable(k.getSuperclass()) ); > 

The following method is modelled from Streams.iterate, however Streams.iterate is designed to create infinite streams. This version has been modified to end when Optional.none() is returned from the fetchNextFunction.

private Stream iterate( T seed, Function fetchNextFunction ) < Objects.requireNonNull(fetchNextFunction); Iteratoriterator = new Iterator() < private Optionalt = Optional.ofNullable(seed); public boolean hasNext() < return t.isPresent(); >public T next() < T v = t.get(); t = fetchNextFunction.apply(v); return v; >>; return StreamSupport.stream( Spliterators.spliteratorUnknownSize( iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE), false ); > 

Источник

Оцените статью