有没有办法实例化匿名内部类中定义的类? [英] Is there any way to instantiate a class defined in anonymous inner class?

查看:164
本文介绍了有没有办法实例化匿名内部类中定义的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我随机写了一个代码&遇到了一个问题:如何实例化在匿名内部类中定义的E类(如下所示);喜欢:

I was randomly writing a code & encountered a problem: how to instantiate class E (shown below) which is defined within an anonymous inner class; like:

 A c = new A() {
   class E{ //Statements
     }
 };


推荐答案

你不能编写一个使用普通程序的程序调用 new 来执行此操作:为了实例化类,它必须具有名称。匿名内部类,如该术语所暗示的,具有名称。

You can't write a program that uses an ordinary call to new to do that: in order for a class to be instantiated, it must have a name. Anonymous inner classes, as that term implies, do not have a name.

因此,在该匿名内部类中存在的类也没有名称;因此无法在该匿名内部类的外部实例化。

Thus a class that exists within that anonymous inner class also has no name; thus it can not be instantiated outside of that anonymous inner class.

您可以使用反射即可。请参阅我的Test.java:

But you can use reflection. See my Test.java:

import java.util.*;
import java.lang.reflect.*;

class B { 
  B() { System.out.println("B"); }
  void foo() { System.out.println("B.foo"); }
}

public class Test{
  B b;
  void bar() {
    b = new B() {
          class C { C() { System.out.println("inner C"); } }
          void foo() { System.out.println("inner foo"); }
    };
    b.foo();
}
public static void main(String[] args) throws Exception {
    Test test = new Test();
    test.bar();

    Class<?> enclosingClass = Class.forName("Test$1");
    Class<?> innerClass = Class.forName("Test$1$C");

    Constructor<?> ctor = innerClass.getDeclaredConstructor(enclosingClass);
    Object innerInstance = ctor.newInstance(test.b);
  }
}

打印:

B
inner foo
inner C

所以,是的,鉴于我们可以在运行时使用 mangled 类名 Test $ 1 $ C 并且该反射允许我们在运行时实例化对象(参见在这里了解详情),最终答案是:是的,它是
可能

So, yes, given the fact that we can use the mangled class name Test$1$C at runtime, and that reflection allows us to instantiate objects at runtime, too (see here for details), the final answer is: yes, it is possible.

但仅限于记录:这并不意味着在实际代码中应该做这样的事情。这是培养创造力的一个很好的小谜题;但是不适合现实世界中的任何东西。

But just for the record: that doesn't mean at all that one should ever do something like this in real code. This is a nice little puzzle to train creativity; but not suited for anything in the real world.

在现实世界中,匿名内部类中的内部类是设计错误。故事结束。

In the real world, an inner class within an anonymous inner class is a design bug. End of story.

这篇关于有没有办法实例化匿名内部类中定义的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆