通过反射操作标识为包内访问权限的类

本文介绍了如何通过反射技术操作具有包内访问权限的Java类,包括获取类的Class对象,设置构造器权限,创建对象并访问私有内容。
package reflecttest.li;

class Test {
    private String as = "It's fucking reflecting too!";
    public String bs = "Reflect please!";
    protected String cs = "Wait for reflecting.";
    private void print(){
        System.out.println("This is only a class for allowing to interview in package.");
    }
    protected String pef(){
        return "What do you want to do?";
    }
}
package reflect.li;


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

public class OperateAnything {
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, InvocationTargetException{
        Class test = null;
        Object obj = null;
        Constructor[] constructor;
        try{
            test = Class.forName("reflecttest.li.Test");
            constructor = test.getDeclaredConstructors();
            System.out.println(constructor.length);
            constructor[0].setAccessible(true);
            obj = constructor[0].newInstance();
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        Method[] methods = test.getDeclaredMethods();
        Field[] fields = test.getDeclaredFields();
        for(Method m : methods){
            m.setAccessible(true);
            System.out.println(m.getName());
            m.invoke(obj);
        }
        for (Field f : fields){
            f.setAccessible(true);
            System.out.println(f.getName() + " " + f.get(obj));
        }
    }
}

一般步骤:获得该类的class对象,展示它的所有构造器,在其中选择一个合适的构造器,用setAccessible方法将权限放开,然后为其创建对象,再然后就为所欲为了<( ̄︶ ̄)>。
不过访问私有内容之前,都要先将它的权限放开。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值