我有一個對象將一些工作委派給另一個實現接口的對象。然後,我創建了實現這個接口的匿名類,我想從這些信息中獲得信息。如何從匿名類中獲取不同類型的數據
可以使用一個大小爲1的最終數組作爲指向primitve的數據與匿名類共享數據嗎?
這裏是我的意思工作的例子:
public class ExampleClass
{
public static final int INVALID_VALUE = -1;
public static void main(final String[] args)
{
final int[] buffer = { INVALID_VALUE }; // buffer is created
final InterfaceA iaObject = new InterfaceA()
{
@Override
public void doStuff(final String paramA)
{
buffer[0] = paramA.length(); // buffer is filled in anonymous class
}
};
final ClassA objA = new ClassA(iaObject);
objA.doStuff("hello, world");
if (buffer[0] == INVALID_VALUE) // buffer is used
{
System.err.println("Invalid length !");
}
else
{
System.err.println("The length is : " + Integer.toString(buffer[0]));
}
}
public static class ClassA
{
private final InterfaceA iaObject;
public ClassA(final InterfaceA iaObject)
{
this.iaObject = iaObject;
}
public void doStuff(final String paramA)
{
this.iaObject.doStuff(paramA);
}
}
public static interface InterfaceA
{
void doStuff(String paramA);
}
}
感謝
爲什麼不讓doStuff返回int呢? –
您應該使用int而不是數組,因爲您只使用一個位置 –
@ Zim-ZamO'Pootertoot doStuff不會返回int,因爲我有時需要布爾值,String和其他類型的值。 – phil