简体   繁体   English

如何访问我无法修改的类中的包保护变量

[英]How to access package-protected variable in class I cannot modify

I have a variable that is in a package, where I can neither modify the package or that class and I need to access it is there any way I can do this.我有一个位于包中的变量,我既不能修改包也不能修改该类,我需要访问它,有什么办法可以做到这一点。 I can not modify com.archi.hello or the contents of it我无法修改 com.archi.hello 或其内容

For Example:例如:

com.archi.hello: com.archi.hello:

class obj:对象类:

public class obj () { 
    int j = 123;
    int getJ () {
        return j;
    } 
}

com.archi.newpackage: com.archi.newpackage:

public class getJo () { 
    int jo;
    obj obj = new obj();
    jo = obj.getJ(); // THIS DOES NOT WORK BECAUSE THE GETTER IS NOT 
    PUBLIC 
}

I need to set jo to j without modifying com.archi.hello in any way, and yes i have tried extending the obj.我需要在不以任何方式修改 com.archi.hello 的情况下将 jo 设置为 j,是的,我已经尝试扩展 obj。 Is there anyway to do this?有没有办法做到这一点?

There are 2 possible cases to get value of j :有两种可能的情况可以获得j值:
Case 1: Because in your example, class obj is public and int j with default visibility => j as a public.情况 1:因为在您的示例中,类obj是公共的,而int j具有默认visibility => j作为公共。 Read this about default access modifier 阅读有关默认访问修饰符的内容

public class obj () { 
    int j = 123; // not declared modifier => modifier is public because obj class is pulic
    int getJ () { // this method is private
        return j;
    } 
}

just do thiss to get value of j :只需这样做即可获得j值:

obj objInstance = new obj();
int valueOfJ = objInstance.j;

Case 2: private int j with private access modifier so it is invisible completely with outside.情况 2: private int j带有私有访问修饰符,因此在外部完全不可见。 In the encapsulation priciple of Java, it not allow to access or modify j official way.在Java的encapsulation priciple中,不允许以官方方式访问或修改j But, you can use some trick to get value j .但是,您可以使用一些技巧来获取值j

public class obj () { 
    private int j = 123; // declared modifier => modifier is private
    int getJ () { // this method is private
        return j;
    } 
}

How to get j如何获得j

obj objInstance = new obj();
java.lang.reflect.Method method = objInstance.getClass().getDeclaredMethod("getJ");
method.setAccessible(true);
int valueOfJ = (int)method.invoke(objInstance);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM