gpt4 book ai didi

java - 如何从匿名类中获取不同类型的数据

转载 作者:行者123 更新时间:2023-11-30 09:23:24 27 4
gpt4 key购买 nike

我有一个对象将一些工作委托(delegate)给另一个正在实现接口(interface)的对象。然后,我正在创建实现此接口(interface)的匿名类,我想从中获取信息。

是否可以使用大小为 1 的最终数组作为指向基元的指针来与匿名类共享数据?

这是我的意思的一个工作示例:

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);
}
}

谢谢

最佳答案

建议:为什么不对输出参数使用泛型?

interface InterfaceA {

public <T> void doStuff( String paramA, Holder<T> holder );
}

class Holder<T> {

public T t;
}

完整示例:

public class ExampleClass
{
public static final int INVALID_VALUE = -1;

public static void main(final String[] args)
{
final InterfaceA< Integer > iaObject = new InterfaceA< Integer >() {
@Override
public Integer doStuff( String paramA, Holder<Integer> holder ) {
return holder.value = paramA.length();
}
};

final ClassA<Integer> objA = new ClassA<>( iaObject );
int result = objA.doStuff("hello, world", new Holder<>( INVALID_VALUE ));
if( result == INVALID_VALUE ) {
System.err.println("Invalid length !");
}
else {
System.err.println("The length is : " + Integer.toString( result ));
}
}

public static class ClassA<T> {
private final InterfaceA<T> iaObject;

public ClassA( final InterfaceA<T> iaObject_ ) {
this.iaObject = iaObject_;
}

public T doStuff( final String paramA, Holder<T> holder ) {
return this.iaObject.doStuff( paramA, holder );
}
}

public static interface InterfaceA<T> {
public T doStuff( String paramA, Holder<T> resultHolder );
}

public static class Holder<T> {

public T value;

public Holder( T value_ ) {
value = value_;
}
}
}

关于java - 如何从匿名类中获取不同类型的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045300/

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