public class Student {
private String name;
private String password;
private int money;
public Student() {
super();
}
public Student(String name, String password, int money) {
super();
this.name = name;
this.password = password;
this.money = money;
}
@Override
public String toString() {
return "Student [name=" + name + ", password=" + password + ", money=" + money + "]";
}
}
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* @author weiyaqiang
*泛型类的案例
*/
public class TestDemo {
//测试泛型类(参数是一个泛型类)
public static <T> List getAll(T t) {
List<T> list =new ArrayList<T>();
list.add(t);
return list;
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
//测试泛型类
Student s=new Student("zhangsan", "sd", 123);
List list = getAll(s);
System.out.println(list.get(0).toString());
//使用反射获取属性的名称
Class<? extends Student> class1 = s.getClass();
Field[] declaredFields = class1.getDeclaredFields();
for(Field d:declaredFields) {
System.out.println(d.getName());
}
//根据已知的字段名称,设置属性值
Field name = class1.getDeclaredField("name");
name.setAccessible(true);
Object field_name = name.get(s);
System.out.println("name:"+field_name);
}
}