java反射 1

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 {

/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Class clazz = User.class;
// clazz = Bean.class;
Object obj = create(clazz);
System.out.println(obj);

System.out.println("---------");
invoke1(obj, "showName");

System.out.println("---------");
field(clazz);
}

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[] ms = obj.getClass().getDeclaredMethods();
ms = obj.getClass().getMethods();
for (Method m : ms) {
// System.out.println(m.getName());
if (methodName.equals(m.getName()))
m.invoke(obj, null);
}

Method m = obj.getClass().getMethod(methodName, null);
m.invoke(obj, null);
}

static void field(Class clazz) throws Exception {
Field[] fs = clazz.getDeclaredFields();
//fs = clazz.getFields();
for (Field f : fs)
System.out.println(f.getName());
}

static void annon(Class clazz) throws Exception {
Annotation[] as = clazz.getAnnotations();
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值