反射(五)------调用特定的属性、方法、构造函数和静态方法

主体代码参看(反射(二))[https://www.cnblogs.com/SnailsRunning/p/10253633.html]

测试代码

package day19;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.junit.Test;

public class TestSpecial {
    /**
     * 调用特定的属性 ;
     * @throws Exception
     */
    @Test
    public void method1() throws Exception {
        Class clazz = Class.forName("day19.Person");
        //公共的属性(public修饰);
        Field field1 = clazz.getField("name");
        //必须要有一个显示的空构造函数
        Person p = (Person) clazz.newInstance();
        System.out.println(p);
        field1.set(p, "Jack");
        System.out.println(p);
        
        //所有的(public、protected、default和private)
        Field field2 = clazz.getDeclaredField("age");
        //这里age被private修饰所以需要设置是否可以被访问;
        field2.setAccessible(true);
        field2.set(p, 20);
        System.out.println(p);

    }
    @Test
    public void method2() throws Exception {
        //公共方法;
        Class clazz = Class.forName("day19.Person");
        Method method1 = clazz.getMethod("toString");
        //调用指定的带参数构造函数;
        Constructor constructor = clazz.getConstructor(String.class,int.class);
        Person p = (Person)constructor.newInstance("Rose",19);
    
        method1.invoke(p);
        System.out.println(p);
        
        //该类所有的方法
        //调用私有方法;
        Method mehtod2 = clazz.getDeclaredMethod("display");
        mehtod2.setAccessible(true);//由于display方法被private修饰,所以需要设置可访问;
        mehtod2.invoke(p);
        
        //调用带有参数的方法;
        Method method3 = clazz.getDeclaredMethod("show1",String.class);
        method3.invoke(p, "hello");
        
        //调用静态方法;
        Method method4 = clazz.getDeclaredMethod("show2");
        method4.invoke(Person.class);
            
    }
    
    
}

运行结果

709915-20190111164452300-60933365.png

注意

根据权限必要的时候需要设置setAccessible(true)

转载于:https://www.cnblogs.com/SnailsRunning/p/10255939.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值