简体   繁体   English

访问匿名外部类而不存储变量?

[英]Access anonymous outer class without storing in variable?

Is there a way to access an anonymous outer class? 有没有办法访问匿名外部类? A normal class can be accessed by ClassName.this. ClassName.this可以访问普通类。 This doesn't work, as an anonymous class obviously doesn't have a name. 这不起作用,因为匿名类显然没有名称。 I also tried using the extended class/interface (like Runnable.this) but it doesn't seem like it would work this way. 我也尝试使用扩展类/接口(如Runnable.this),但似乎它不会以这种方式工作。

I'm sure this may be not the best coding style, I'm just curious if it's possible without storing this of the outer in a variable. 我敢肯定这可能不是最好的编码风格,我只是好奇,如果没有将外部存储在一个变量中是可能的。

Example, watch out for outer.this: 例如,注意outer.this:

public class A
{
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (outher.this) {
                            outher.this.notify();
                        }
                    }
                }).start();
                try {
                    synchronized (this) {
                        wait();
                    }
                } catch (final InterruptedException ex) {}
            }
        }).start();
    }
}

No, there is no way to access anonymous classes from anywhere, except from inside them (ie otherwise than by this reference). 不,没有办法从任何地方访问匿名类,除了从它们内部(即不是通过this引用)。 Or by an explicitly declared variable. 或者通过显式声明的变量。

final Runnable r1 = new Runnable() {...};
Runnable r2 = new Runnable() {
    public void run() {
         synchronized(r1) {...}
    }
};

You could add a method to return this middle this . 你可以添加一个方法返回这中间this It would be in scope but not hidden (is that the right term? Shadowed? I forget.). 这将是范围但不隐藏(是正确的术语?暗影?我忘了。)。

public static void main(String[] args) {
    new Thread(new Runnable() {
        Runnable middleThis() { return this; } // <-- this
        @Override
        public void run() {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (middleThis()) {
                        middleThis().notify();

Note, although anonymous inner classes have no name, they still are types. 请注意,虽然匿名内部类没有名称,但它们仍然是类型。 So adding members is visible to the immediate expression ( new X() { Y z; }.z ) and inside. 因此,立即表达式( new X() { Y z; }.z )和内部可以看到添加成员。 You can't do middleThis().middleThis() . 你不能做middleThis().middleThis()

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

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