繁体   English   中英

从 Java 中特定类型的数组中获取项目

[英]Get items from an array of specific oftype in Java

在 C# 中,使用Linq从给定特定类型的数组中检索项目作为通用方法参数是相对直接的:

class SimpleIoC
{
    object[] registrations = new object[] {
        new ServiceA(), new ServiceB(), new ServiceC(), new ServiceA()
    };

    public IEnumerable<T> GetAll<T>() => registrations.OfType<T>();
}
    

var ioc = new SimpleIoC();  
var serviceAs = ioc.GetAll<ServiceA>();

这在 Java 中可以实现吗? 如果是这样,如何?

@Test
public void Testing_stuff() {
    ArrayList<Receives<?>> receivers = new ArrayList<>();
    receivers.add(new TestReceiver("I picked a bad day to give up learning java..."));

    Iterable<Receives<TestMessage>> all = getTheDarnThing(receivers);
}

private <T> Iterable<T> getTheDarnThing(ArrayList<?> list) {

    // help me obi-wan kenobi...
    return list.stream()
                .filter(x -> T.class.isAssignableFrom(x.getClass()))
                .map(x -> (T) x) // unchecked
                .collect(Collectors.toList());
}

另外,是否可以知道泛型参数的T类型?

在 Java 中,你需要传递一些东西来识别类型作为方法的参数,因为像T这样的类型参数只是一个编译时构造。 通常使用Class object:

private <T> List<T> getTheDarnThing(List<?> list, Class<T> klass) {
    return list.stream()
        .filter(klass::isInstance)
        .map(klass::cast)
        .collect(Collectors.toList());
}

这是您可以使用它的方式:

List<Service> services = List.of(new ServiceA(), new ServiceB(), new ServiceC());
List<ServiceA> as = getTheDarnThing(services, ServiceA.class);

请注意,在您的 Java 代码中,列表中的所有对象都是具有不同类型参数的Receives class 的实例。 您将无法在运行时区分其中两个对象,因为类型参数已被删除。 您可以做的是定义专门的类来表示不同类型的“接收”对象。 例如: class TestReceives extends Receives<TestMessage>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM