Java reflection to determine whether the Class is a subclass or parent Class of a Class.

Source: Internet
Author: User

Class c = ArrayList. class;
C. isPrimitive (); // determines whether c is a basic data type.
C. isAssignableFrom (List. class); // determines whether c is a subclass or parent class of the List class.
C. getGenericType (); // obtain the generic type.

Instance: Obtain the generic type in the List <T> set through reflection.
[Java]
Package com.zf.tar get;

Import java. lang. reflect. Field;
Import java. lang. reflect. ParameterizedType;
Import java. lang. reflect. Type;
Import java. util. List;
Import java. util. Map;

Class T {
List <A>;
List <B> B;
// List l;
Map <Integer, String> map;
Int c;
}

Class {}
Class B {}

Public class Test9 {

Public static void main (String [] args ){
Class tc = T. class;
Field [] fields = tc. getDeclaredFields ();
For (Field f: fields ){
Class fc = f. getType ();
If (fc. isPrimitive ()){
System. out. println ("basic data type:" + f. getName () + "" + fc. getName ());
} Else {
If (fc. isAssignableFrom (List. class) {// you can check whether it is a List.
System. out. println ("List type:" + f. getName ());
Type gt = f. getGenericType (); // obtain the generic Type.
ParameterizedType pt = (ParameterizedType) gt;
Class lll = (Class) pt. getActualTypeArguments () [0];
System. out. println ("\ t" + lll. getName ());
}
}
}
}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.