gpt4 book ai didi

Java 编译器给出错误 - 没有类型的封闭实例

转载 作者:行者123 更新时间:2023-12-02 07:08:45 25 4
gpt4 key购买 nike

我设计了一个类:

public class CustomEvent< P, T >
{
/** Facade interface used for adopting user interfaces to our generic class. */
public interface ICaller< P, T >
{
/** callback facade method. */
void call( P parent, T callback, Object... objects );
}

/** Abstract class for simplifying naming in constructor. */
public abstract class Caller implements ICaller< P, T >{}

/** Constructor. */
public CustomEvent( final String name, final P parent, final Caller caller ){}
}

现在我想创建一个此类的实例:

  public class TestClass
{
private final TestEvent mEventOnLoad;

public TestClass()
{
// ERROR here: No enclosing instance of type CustomEvent<P,T> is accessible.
// Must qualify the allocation with an enclosing instance of type
// CustomEvent<P,T> (e.g. x.new A() where x is an instance of CustomEvent<P,T>).
mEventOnLoad = new TestEvent( "onLoad", this, new TestEvent.Caller() {
public void call( TestClass parent, ITestCallbacks callback, Object... objects )
{
// some code here
}
} );
}

private class TestEvent extends CustomEvent< TestClass, ITestCallbacks >
{
public TestEvent( String name, TestClass parent, TestEvent.Caller caller )
{
super( name, parent, caller );
}
};
}

有没有可能以某种方式解决这个问题?我想简化类的命名,而不是长泛型声明,而是使用包含所有需要的类型定义的短抽象类名?

我有一个填充是可能的......但我对 Java 还不太熟悉......

解决方案

    private class TestEvent extends CustomEvent< TestClass, ITestCallbacks >
{
public final static TestEvent Instance = new TestEvent( null, null, null );

public TestEvent( String name, TestClass parent, TestEvent.Caller caller )
{
super( name, parent, caller );
}
};

public TestClass()
{
mEventOnLoad = new TestEvent( "onLoad", this, TestEvent.Instance.new Caller() {
public void call( TestClass parent, ITestCallbacks callback, Object... objects )
{
// some code here
}
} );
}

最佳答案

调用者需要被声明为静态的。现在声明的 Caller 是一个内部类,这意味着它只能从现有父类(super class)的实例创建。例如,如果您有:

class A{
class B{}
}

然后要创建 B 类的东西,您需要:

A a = new A();
B b = new a.B();

那是因为B是一个内部类;它只能存在于某些 A 的上下文中。您可能不需要它成为内部类,因此将其声明为静态的,使其像普通类一样工作。或者,如果不需要,请将其删除。

关于Java 编译器给出错误 - 没有类型的封闭实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8129706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com