Java reflection, which determines whether class is a subclass of a class or a parent class __class

Source: Internet
Author: User

Class C = arraylist.class;

C.isprimitive (); Determine if C is a basic data type

C.isassignablefrom (List.class); Determine if C is a subclass of the list class or a parent class

C.getgenerictype (); Get generic type


Instance: the generic type in the List<t> collection is obtained by reflection

Package com.zf.target;

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>  A;
	List<b>  B;	List l;
	Map<integer, string> map;
	int c;
}

Class A {}
class b{} public

class test9{public

	static void Main (string[] args) {
		class TC = t.class;< c20/>field[] fields = Tc.getdeclaredfields ();
		for (Field f:fields) {
			Class FC = F.gettype ();
			if (fc.isprimitive ()) {
				System.out.println ("Base data type:" + f.getname () + "  " + fc.getname ());
			} else{
				if (Fc.isassignablefrom (List.class)) {//To determine whether the list
					System.out.println ("list type:" + f.getname ());
					Type GT = F.getgenerictype ();	Get generic type
					parameterizedtype pt = (parameterizedtype) gt;
					Class lll = (Class) pt.getactualtypearguments () [0];
					System.out.println ("\t\t" + lll.getname ());}}}}
	



Related Article

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.