需求:定义一个Boss类,其中有一个属性为一个泛型类对象,通过反射获取该对象的某个属性
1 定义一个Boss类(getGeneraticTypeName方法用于获取泛型T的名为“name”、“、age”的属性值):
package Reflect;
/**
* @Classname Boss
* @Description TODO
* @Date 2022/5/4 14:20
* @Created by jiawe
*/
public class Boss<T> {
T t;
public Boss(T t) {
this.t = t;
}
public String getGeneraticTypeName() {
try {
return (String) t.getClass().getDeclaredField("name").get(t) + "=====" + (int) t.getClass().getDeclaredField("age").get(t);
} catch (IllegalAccessException e) {
return "No such attribute";
} catch (NoSuchFieldException e) {
return "No such attribute";
}
}
}
2:定义一个Person类,添加name、age属性
package Reflect;
/**
* @Classname Person
* @Description TODO
* @Date 2022/5/4 14:18
* @Created by jiawe
*/
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
}
3 编写代码测试
package Reflect;
/**
* @Classname Test
* @Description TODO
* @Date 2022/5/4 14:23
* @Created by jiawe
*/
public class Test {
public static void main(String[] args) {
Person jake = new Person("jake", 15);
Boss<Person> personDemo = new Boss<>(jake);
System.out.println(personDemo.getGeneraticTypeName());
}
}
4 输出结果
>>>
jake=====15
Process finished with exit code 0