0
class A<Type>{

    private Type id;

}

class B extends A<String>{


}

B b = new B();
Field idField = //reflection code to get id field

How from "idField" , we can get the exact type of idField , means String instead of Type ?

Jeffrey
  • 42,428
  • 7
  • 84
  • 138
kycdev
  • 95
  • 2
  • 6
  • What is the purpose of doing this? I can't see any possible use for this. In the example given, it is obvious that the type is String because the class is defined that way, and won't be changing. – tcooc Jun 12 '12 at 23:11
  • 2
    I don't see how this is an exact duplicate of the other question. In this specific case, the type is available at runtime. – Tom Hawtin - tackline Jun 12 '12 at 23:25
  • The real duplicate is here: [Check if field type is same as generic type in java](http://stackoverflow.com/q/2758582/697449) – Paul Bellora Jun 13 '12 at 02:31
  • @digitalFresh I want to know the field type at runtime in order to set a value (String , int or whatever) – kycdev Jun 13 '12 at 09:15
  • @TomHawtin-tackline yes the type is available at runtime. but how to get it? – kycdev Jun 13 '12 at 09:17
  • @kycdev Need a couple more reopens before an answer can be added... (Although I'm pretty sure whatever you are planning is a bad idea. If a plan involves reflection, it usually is.) – Tom Hawtin - tackline Jun 13 '12 at 10:06

1 Answers1

1

I'm not exactly sure what you are trying to achieve. But I'm guessing that you would like to determine the concrete type of field 'id'.

    public class A<T>{
    public T id;
    public Class<T> idType;

    public A(){
        idType = (Class<T>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }
}

public class B extends A<String>{

}

public static void main(String[] args) throws Exception {
    B b = new B();
    System.out.println(b.idType);
}

The last sysout statement in the above code snippet will print 'java.lang.String'.

This is a technique that is very commonly used when writing generic functionality in the base class.

Sashi
  • 1,457
  • 11
  • 12