java中反射将取得的类实例化_反射机制实例化类,并获取类中的属性、方法、和构造器...

1.先写一个JavaBean类:

package com.buaa.reflectTest;

public class User {

private int id;

private int age;

private String uname;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getUname() {

return uname;

}

public void setUname(String uname) {

this.uname = uname;

}

public User(int id, int age, String uname) {

super();

this.id = id;

this.age = age;

this.uname = uname;

}

public User() {

}

}

2.利用反射机制获取do something....

package com.buaa.reflectTest;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;

import java.lang.reflect.Method;

public class Demo01 {

public static void main(String[] args) {

String path = "com.buaa.reflectTest.User";

try {

Class clazz = (Class)Class.forName(path);

//get constructor

Constructor con = clazz.getDeclaredConstructor(int.class,int.class,String.class);

User u = (User)con.newInstance(1,19,"maomi");

System.out.println(u.getUname());

//get Method

Method m = clazz.getDeclaredMethod("setAge", int.class);

m.setAccessible(true);

m.invoke(u, 20);

System.out.println(u.getAge());

//get field

Field f = clazz.getDeclaredField("id");

f.setAccessible(true); //设置访问权限

f.set(u, 3);

System.out.println(u.getId());

} catch (Exception e) {

e.printStackTrace(http://www.amjmh.com);

}

}

}

---------------------

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值