[英]How to create an anonymous class using a method that returns a reference to a class
I want to create an anonymous class using a method that returns an instance of a class我想使用返回类实例的方法创建一个匿名类
class FirstClass {
public FirstClass() {
System.out.println("First class created");
}
}
class SecondClass {
public SecondClass() {
System.out.println("Second class created");
}
public FirstClass getFirstClass() {
return new FirstClass();
}
}
public class Ex1 {
public FirstClass getFirstClass() {
return new FirstClass();
}
public static void main(String[] args) {
//here is the problem
Object obj = new SecondClass().getFirstClass() {
{
System.out.println("Anonymous class created");
}
};
}
}
I expect program to work by creating the anonymous class, but it gives me a syntax error.我希望程序通过创建匿名类来工作,但它给了我一个语法错误。 Any solutions or workarounds are accepted.接受任何解决方案或变通方法。 Thanks谢谢
You cannot create an anonymous class based on return value of a method.您不能基于方法的返回值创建匿名类。 Anonymous classes can only be created upon creation of the object , meaning, it can only be created using a constructor.匿名类只能在创建对象时创建,这意味着它只能使用构造函数创建。
Your best bet would be to just create FirstClass
directly, and override the initializer, like so:最好的办法是直接创建FirstClass
,并覆盖初始化程序,如下所示:
new FirstClass() {
{
System.out.println("This is from inside anon!");
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.