dmay
dmay

Reputation: 1315

Get specific property of object using java Reflection

I have class User which have different objects like country,address,car and many others. All embedded objects have userid property which is long. I have User object, i want to set userid property of all embedded objects to specific value or null using java reflection. Otherwise i have to write methods for each different object.

Upvotes: 0

Views: 4163

Answers (3)

Nivas
Nivas

Reputation: 18334

Unless there is a specific reason to use reflection, it is better not to use it.

If you are looking for using reflection because it will be convinient or it will take fewer lines of code/make code readable, then note that this is not true.

Generally reflection code is less readable, and you are almost always better off using the normal way of invoking methods.

Reflection is suitable when, say, your method names are known only at runtime (via a properties file or something)

If for any reason, you need reflection, see this.

Upvotes: 1

Faisal Feroz
Faisal Feroz

Reputation: 12785

You can use Apache Common's ReflectionUtils and BeanUtils class to help you out. ReflectionUtils has several helper methods that can help in discovering properties you are interested in and BeanUtils has helper methods to populate the values of properties/fields.

Upvotes: 5

Stan Kurilin
Stan Kurilin

Reputation: 15792

If I understood task in correct way, you can do it without reflection.

abstract class Embedded {
    private static final Set<Integer> obj = ...;
    {
        //init obj
    }
    protected Embedded(int id){
        set.add(id);
    }
    public static Set<Integer> getAllIDs(){
        return obj; //return copy or immutable collection
    }
}

Upvotes: 0

Related Questions