简体   繁体   English

引用一个匿名类?

[英]Reference an anonymous class?

I am developing a plugin for an RCP application. 我正在为RCP应用程序开发一个插件。 Within the plugin.xml , I need to register certain classes at a given extension point. plugin.xml ,我需要在给定的扩展点注册某些类。 One of these classes is an anonymous (?) class defined like this: 其中一个类是一个匿名(?)类,定义如下:

package de.me.mypackage;

import org.something.AnotherClass;

public class ClassOne {
  ...
  public static AnotherClass<ClassOne> getThat() {
    return new AnotherClass<ClassOne>() {
      ...
    };
  }

} }

Is there any way to reference AnotherClass<ClassOne> within the plugin.xml? 有没有办法在plugin.xml中引用AnotherClass<ClassOne>

I already tried something like de.me.mypackage.ClassOne$AnotherClass but that does not work. 我已经尝试了类似de.me.mypackage.ClassOne$AnotherClass东西,但这不起作用。 Do I have to declare that class within its own file to be able to reference it? 我是否必须在自己的文件中声明该类才能引用它?

As far as I know, it would have a numeric index: 据我所知,它会有一个数字索引:

class Bla {
  public static void main(String[] args) {
    (new Runnable() {
      public void run() {
        System.out.println(getClass().getName()); // prints Bla$1
      }
    }).run();
  }
}

After compiling, you get: 编译完成后,您会得到:

$ ls *.class
Bla$1.class Bla.class

That said, you can't rely on the numbering in case the source file is modified. 也就是说,如果修改源文件,则不能依赖编号。

Can you instead define a static inner class, like: 您可以改为定义static内部类,例如:

public class ClassOne {

  public static class MyClass extends AnotherClass<ClassOne> {
    public MyClass(/* arguments you would pass in getThat()? */) {
      ...
    }
    ...
  }

  public static AnotherClass<ClassOne> getThat() {
    return new MyClass(...);
  }
}

I need to say the obvious here - you should make it a named class if you want to refer to it. 我需要在这里说明显的 - 如果你想引用它,你应该把它变成一个命名类。 Whether you can access it otherwise is a technical curiosity (that I don't happen to know the answer to), not something you should actually do in production. 你是否可以访问它是技术上的好奇心(我不知道答案),而不是你应该在生产中实际做的事情。

The dollar sign only comes into play in the class's binary name ; 美元符号只在类的二进制名称中起作用; in Java source, just use de.me.mypackage.ClassOne.AnotherClass.class . 在Java源代码中,只需使用de.me.mypackage.ClassOne.AnotherClass.class

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

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