Muhammad Ahmed AbuTalib
Muhammad Ahmed AbuTalib

Reputation: 4322

retrieving instance from Class object java

I understand that the following can be done .

User user = new User();
user.setUsername("a");
user.setPassword("abc");

 Class c = user.getClass();

However I have a situation in which I have to extract the instance information from the variable "c"

Is it even possible ? . We do have a c.newInstance() method but that would create a new instance of the object User. I need to access the existing instance of the User , which was responsible for creating the "c" variable in the first place .

Thanks

-----------EDIT----------- Looking at the comments I understood that my concept of getClass was flawed . What I want to achieve is that I need a method which would iterate over an object's getters . So what would be the signature of such ?

I was thinking on the lines of

public static <T> List<NameValuePair> entityConvert1(Class<T> entity)

however as per all the comments , I understand passing the Class wont send in any instance specific information in the method .

I need a torch here .

Upvotes: 2

Views: 595

Answers (2)

Rohit Jain
Rohit Jain

Reputation: 213391

Update:

It seems like, you just want to get the getter methods from your class, and invoke it to get the value for a particular instance.

You can get all the getters using Introspector. Write a generic method, taking 2 arguments - Class<T>, and T types:

public static <T> void executeGetters(Class<T> clazz, T instance) throws Exception {
    BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

    for(PropertyDescriptor propertyDescriptor: beanInfo.getPropertyDescriptors()){
        // Get Method instance used for reading this property
        Method method = propertyDescriptor.getReadMethod();
        // Invoke this method on 'instance'. 
        System.out.println(method.invoke(instance));
    }
}

Now, invoke this method as:

executeGetters(User.class, user);

This will print the value of all the properties for user instance. Note, if there is a getter method missing for the User class, this Method instance will be null, and you might get a NPE. You need to check for that.

Upvotes: 4

Mike Thomsen
Mike Thomsen

Reputation: 37526

I need to access the existing instance of the User , which was responsible for creating the "c" variable in the first place

Can't be done because there is no link between the getClass() method's result and c. The problem is that the Class c represents an instance of the type of c not the particular instance which is user. Class itself is a representation of the bytecode file loaded by the JVM and what it exposes so you can do reflection operations. It's not even directly analogous to the actual User class represented by the bytecode. It's more low level than what you're thinking.

Upvotes: 2

Related Questions