javaclassruntime-type

Passing a class as a parameter in a method and using this parameter in an If statement


I would like to have something like this:

public static List<Type> getProtocolls(Class clazz, Transaction trx) {
    Iterator<Type> iterator = trx.getContext().getProtocolls()
    List<Type> list = null;
    while (iterator.hasNext()) {
        if (iterator.next() instanceof clazz) {
            list.add(iterator.next())
        }       
    }
    return list;
}

I am talking mainly about this part: (iterator.next() instanceof clazz) - is this even possible to pass Class as a parameter like this? Eclipse says "clazz cannot be resolved to a type".


Solution

  • You could use the isAssignableFrom method. Also, note you have two calls to next() in the loop, so you'll be skipping half the elements - you should extract the result of this call to a local variable:

    while (iterator.hasNext()) {
        Type t = iterator.next();
        if (clazz.isAssignableFrom(t.getClass())) {
            list.add(t)
        }       
    }
    

    EDIT:
    As @Fildor noted in the comments, you also forgot to initialized list. Instead of initializing to null list you currently have, you should have something down the lines of List<Type> list = new LinkedList<>();.