JAVA反射示例

 public static void main(String[] args) throws Exception {
        
        Class pClass = Class.forName("jdj.Person");
        //遍历整个控制器
        Constructor[]  constructors=pClass.getDeclaredConstructors();
        for(Constructor con:constructors) {
        	System.out.println(con);
        }
        //通过控制器创建对象
        Constructor con_1=pClass.getConstructor(String.class);
        con_1.setAccessible(true); //private类都需要进行暴力反射才可以使用
        Person p1=(Person) con_1.newInstance("aaa");
        //添加基本类型的数据
        Field nameField=pClass.getDeclaredField("name"); //姓名
        nameField.setAccessible(true);
        nameField.set(p1, "张三");
        System.out.println(nameField.get(p1));
        Field ageField=pClass.getDeclaredField("age"); //年龄
        ageField.set(p1, 45);
        System.out.println(ageField.get(p1));
        Field sexField=pClass.getDeclaredField("sex"); //性别
        sexField.set(p1, '男');
        System.out.println(sexField.get(p1));
        Field heightField=pClass.getDeclaredField("height");
        heightField.set(p1, 175);
        System.out.println(heightField.get(p1));
        //添加方法类型
        Method method1=pClass.getMethod("run");
        method1.invoke(p1);
        System.out.println(method1);
        Method method2=pClass.getMethod("run",String.class);
        method2.invoke(p1,"李逵");
        System.out.println(method2);
        Method method3=pClass.getDeclaredMethod("flay",String.class);
        method3.setAccessible(true);
        method3.invoke(p1, "松江");
        System.out.println(method3);
        //注意: public类的方法 getMethod和getDeclaredMethod两种都可以调取 private只能使用getDeclaredMethod调取
        
    } 

以下为要调用的person类中的方法 控制器  基本数据变量

private String name;
	public Integer age;
	Character sex;
	protected Integer height;
	
	private Person() {
		
	}
	
	
	public Person(String name,Integer age,Character sex,Integer height ) {
		this.name = name;
		this.age = age;
		this.sex = sex;
		this.height = height;
	}
	public Person(String name) {
		this.name = name;
	}
	//在java当中 方法名和参数列表
	public void run() {
		System.out.println("人跑的很快");
	}
	public void run(String name) {
		System.out.println(name+"人跑的很快");
	}
	private void flay(String name) {
		System.out.println(name+"会飞");
	}
	
	Integer getAge() {
		return age;
	}
	
	public void hhh(Integer age,Character sex) {
		System.out.println(age + " " + sex);
	}

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值