简体   繁体   English

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

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

In C#, it is relatively straight forward to retrieve items from an array of given a specific type as a generic method parameter using Linq :在 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>();

Is this achievable in Java?这在 Java 中可以实现吗? If so, how?如果是这样,如何?

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

Also, is it possible to know what the type of T is for the generic parameter?另外,是否可以知道泛型参数的T类型?

In Java you need to pass something to identify the type as a parameter to the method, because type parameters like T are only a compile time construct.在 Java 中,你需要传递一些东西来识别类型作为方法的参数,因为像T这样的类型参数只是一个编译时构造。 Often a Class object is used:通常使用Class object:

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

This is how you can use it:这是您可以使用它的方式:

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

Note that in your Java code, all objects in your list are instances of Receives class with different type parameters.请注意,在您的 Java 代码中,列表中的所有对象都是具有不同类型参数的Receives class 的实例。 You won't be able to tell two of these objects apart at run time, since the type parameter is erased.您将无法在运行时区分其中两个对象,因为类型参数已被删除。 What you can do is define specialized classes to represent the different types of "Receives" objects.您可以做的是定义专门的类来表示不同类型的“接收”对象。 For example: class TestReceives extends Receives<TestMessage>例如: class TestReceives extends Receives<TestMessage>

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

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