我設計一個類類型的無外圍實例:Java編譯器提供了錯誤 -
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
}
});
}
可能重複的[Java - 沒有封閉實例類型Foo是可訪問的](http://stackoverflow.com/questions/9560600/java-no-enclosing -instance-of-type-foo-is-accessible) – Raedwald