简体   繁体   中英

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 :

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? 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?

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. Often a Class object is used:

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. 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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