简体   繁体   English

如何通过另一种方法访问本地内部类的字段?

[英]How can I access a field of a local-inner class from another method?

Consider the field bar of the local-inner class MyValue : 考虑本地内部类MyValue的字段bar

public class C {

public static void main(String x[]) {

    class MyValue implements IValue {
    String bar = "bar";
    public String  getValue() {
        return "my value";
    } 
    }
    MyValue myValue = new MyValue();

    D d = new D();
    d.accessBar(myValue);
}
}      

which implements the IValue interface: 它实现了IValue接口:

interface IValue {
public String getValue();
}

How can I access the field bar from another function (outside of main ), let's say in class D : 我如何从另一个函数(在main之外)访问字段bar ,比如在类D说:

class D {
public void accessBar(IValue value) {
    String info = value.getValue() + value.bar;
}   
}

If you need to access the pass key of a ship and you only have the IShip interface, then IShip should have a getPassKey() method, basically. 如果您需要访问飞船的通行键,并且仅具有IShip接口,则IShip应该基本上具有getPassKey()方法。 Even if you could cast to ShipAddress within the method, you shouldn't do so - you should make the parameter type for the calculatedInfo method suitable for all the operations the method requires. 即使你可以转换为ShipAddress的方法中,你不应该这样做-你应该做的参数类型calculatedInfo适合所有的方法需要的操作方法。

You could access it via reflection, but that would be horribly brittle and I'd strongly recommend that you don't do that. 可以通过反射访问它,但这将非常脆弱,我强烈建议您不要这样做。

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

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