package com.mengya.test;
import java.util.Date;
public class User {
private int id;
private String name;
private Date birthday;
private float money;
public User() {
}
public User(String name) {
this.name = name;
}
public User(float money) {
this.money = money;
}
public void showName() {
System.out.println(this.name);
}
@Override
public String toString() {
return "id=" + this.id + " name=" + this.name + " birthday="
+ this.birthday + " money=" + this.money;
}
private void test() {
}
public int getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void setBirthday(java.sql.Date birthday) {
this.birthday = birthday;
}
public float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
}
测试:
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = User.class;
Object obj = create(clazz);
System.out.println(obj);
System.out.println("---------");
invoke1(obj, "showName");
System.out.println("---------");
field(clazz);
}
//通过Class构造对象
static Object create(Class clazz) throws Exception {
Constructor con = clazz.getConstructor(String.class);
Object obj = con.newInstance("test name");
return obj;
}
//根据方法名称,调用对象的方法
static void invoke1(Object obj, String methodName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException, Exception, NoSuchMethodException {
//Method是一个对象在java.lang.reflect.Method中,包含有方法的信息
Method[] ms = obj.getClass().getDeclaredMethods();
//得到对象自己的方法包括Privete方法,但不放包括父类的方法
ms = obj.getClass().getMethods();
//得到对象所有public方法,也包括来自父类的方法.通常用个
for (Method m : ms) {//循环遍历对象中的所有方法
// System.out.println(m.getName());//得到所有方法名称
if (methodName.equals(m.getName()))
m.invoke(obj, null);//调用方法名为参数中methodName值的方法,该方法(所找到的那个方法)没有参数
}
Method m = obj.getClass().getMethod(methodName, null);//这样是根据方法名称和方法参数去要找特定的方法.null表示该方法没有参数
//obj.getClass().getMethod(methodName,String.class);//这样是根据方法名称和方法参数去要找特定的方法.该方法的参数为String
m.invoke(obj, null);//调用obj对象的这个方法
}
//得到对象的属性
static void field(Class clazz) throws Exception {
Field[] fs = clazz.getDeclaredFields();//所有属性都能得到,包括private属性也能得到
//fs = clazz.getFields();//public属性能得到
for (Field f : fs)
System.out.println(f.getName());//输出所属性的名字
}
//得到对象中的Annotation如:@Override
static void annon(Class clazz) throws Exception {
Annotation[] as = clazz.getAnnotations();
for(Annotation an : as){
System.out.println(an.toString());
}
}
}