关于反射

package test;

public class Person{
    private String name;
    private int age;
    private  double salary;
    public int abc;
    private void a(String a) {
        a="A";
        System.out.println("this is "+a);
    }
    public void b(String a,int b) {
        a="b";b=3;
        System.out.println("this is "+a+",and it's="+b);
    }
    protected void c() {
        System.out.println("this is c");
    }
    void d(String a,String b) {
        System.out.println("this is "+a+b);
    }
}

 

 

package test;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class GetPerson {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
        //加载类
        Class<?> clazz=Class.forName("test.Person");
        //实例化对象
        Object o=clazz.getConstructor().newInstance();
        System.out.println(o);
        //参数数组
        Field[] fields=clazz.getDeclaredFields();
        //方法数组
        Method[] methods=clazz.getDeclaredMethods();        
        //遍历参数
        for (Field field : fields) {
            //强制读取私有变量
            field.setAccessible(true);
            System.out.println("变量===="+field);
        }
        //便利方法
        for (Method method : methods) {
            //强制读取私有方法
            method.setAccessible(true);
            System.out.println("方法=========="+method);
            //遍历方法的参数
            Class<?>[] paramtypes=method.getParameterTypes();
                //使用不带参数的方法
                if(paramtypes.length==0) {method.invoke(o);continue;}
                Arrays.asList(paramtypes).forEach(System.out::println);        
        }
        //使用d方法
        Class[] patype=new Class[2];
        patype[0]=String.class;
        patype[1]=String.class;
        Method m=clazz.getDeclaredMethod("d", patype);
        m.invoke(o, "AAAA","BBBBB");
    }
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值