-1

I want to get all the fields and it's values from an object of type T. Say I have:

public class Start {

    public void startMethod(){
        Main<GenericType> main = new Main<>();
        main.work(new GenericType());
    }

}

Then there's class Main, where I want the fields of GenericType:

public class Main<T> {

    public void work(T t){
        // Is there a way to get t's fields and values?
    }

}
Washington A. Ramos
  • 874
  • 1
  • 8
  • 25

2 Answers2

0

First,you need to get Class of T,then through reflection ,you can get all fields.

abstract class A<T> {  
    Class<T> clazz;  
    void doGetClass() {  
        Type genType = this.getClass().getGenericSuperclass();  
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();  
        this.clazz = (Class<T>) params[0];  
    }
}  

but you must instantiate the generic type ,like this,instantiate T to String:

class B extends A<String>{  
} 

then

B b = new B();  
b.doGetClass();// b.clazz is String.class
BlackJoker
  • 3,099
  • 2
  • 20
  • 27
0

Following @BalwinderSingh's answer I came to this:

public void work(T t){
    for(Field f : t.getClass().getDeclaredFields()){
        try {
            f.setAccessible(true);

            String name = f.getName();
            Object value = f.get(object);


        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

It was simpler than I though at the beginning. Thank you all.

Washington A. Ramos
  • 874
  • 1
  • 8
  • 25