简体   繁体   English

通过反射访问子类中超类的私有成员变量

[英]accessing the private memeber variable of super class in the child class through reflection

I have this class that is RMIserviceexporter basically this class is spring remoting now in this there is a int variable named registry port 我有一个这样的类,基本上是RMIserviceexporter,这个类是春季远程处理,因为现在有一个名为注册表端口的int变量。

private int registryPort = Registry.REGISTRY_PORT; // which is set to 1099

and it has setter methods 它有setter方法

public void setRegistryPort(int registryPort) {
    this.registryPort = registryPort;
}

now I have extended this class in later stages that is have i have created a new class abcexpoerter which basically extend RMIserviceexporter , I have to access this registryPort variable of RMIserviceexporter that is the variable name registryPort but i can not access this variable since there is no getter method defined in the parent class now please advise me can i access this private variable value in the extended lass through reflection 现在我在以后的阶段中扩展了该类,即我已经创建了一个新类abcexpoerter,该类基本上扩展了RMIserviceexporter,我必须访问RMIserviceexporter的这个RegistryPort变量,它是变量名RegistryPort,但是我无法访问此变量,因为没有现在在父类中定义的getter方法,请告知我是否可以通过反射在扩展的lass中访问此私有变量值

   class abcexpoter extends RMIServiceExporter
        {
            // now in this class i want to access the registerPort variable value  please advise how can i //access this registry port variable inside this class
        }

You can , but you shouldn't . 可以 ,但不可以 The member is presumably private for a reason . 由于某种原因,该成员可能是私人

This is covered in the Class and java.lang.reflect package documentation: You get the field via getDeclaredField , then force it accessible using setAccessible , then use the relevant getXyz method from Field ( getInt , getString , whatever) to get its value. Classjava.lang.reflect文档中对此进行了介绍:您可以通过getDeclaredField获取字段,然后使用setAccessible强制对其进行访问,然后使用Field的相关getXyz方法( getIntgetString ,无论如何)来获取其值。

For instance, since it's an int : 例如,由于它是一个int

Field field = TheClass.class.getDeclaredField("registryPort");
field.setAccessible(true);
int port = field.getInt(this);

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

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