Get the type of the parent generic type through reflection

If there are the following classes:

father:

 

public class Person<T> {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	
}

 

 

Subclass:

 

public class Student extends Person<Student> {
	private String num;

	public String getNum() {
		return num;
	}

	public void setNum (String num) {
		this.num = num;
	};
	
}

 

 

Get the type method of the parent class generic through reflection:

Class <T> entityClass = (Class <T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; 

 

How to get details:

@Test
	@SuppressWarnings("rawtypes")
	public void testGetSuper(){
		Student student = new Student();
		Class clazz = student.getClass();
		//Get the parent class of this class
		System.out.println("The parent class of this class: "+clazz.getSuperclass());
		// get parent class with generics
		Type type = clazz.getGenericSuperclass();
		System.out.println("Generic parent class: "+type);
		// Get the parameterized type (ie generic)
		ParameterizedType p = (ParameterizedType) type;
		//Generic types may be multiple, get what you need
		Class clazz2 = (Class) p.getActualTypeArguments()[0];
		System.out.println("Type of parent generic: "+clazz2);
	}

 

 

The output is:

The parent class of this class: class com.test.bean.Person

Parent class with generics: com.test.bean.Person<com.test.bean.Student>

Type of parent generic: class com.test.bean.Student

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326313568&siteId=291194637