简体   繁体   English

将类作为方法中的参数传递,并在If语句中使用此参数

[英]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? 我主要在谈论这部分: (iterator.next() instanceof clazz) -甚至有可能像这样将Class传递为参数吗? Eclipse says "clazz cannot be resolved to a type". Eclipse说“ clazz无法解析为一种类型”。

You could use the isAssignableFrom method. 您可以使用isAssignableFrom方法。 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: 另外,请注意,您在循环中对next()进行了两次调用,因此您将跳过一半的元素-您应将此调用的结果提取到局部变量中:

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 . 正如@Fildor在评论中指出的那样,您还忘记了初始化list Instead of initializing to null list you currently have, you should have something down the lines of List<Type> list = new LinkedList<>(); 而不是初始化为当前拥有的null列表,而应该在List<Type> list = new LinkedList<>(); .

You have mention the reference but you have to use the Class there :- 您已经提到了引用,但必须在其中使用Class:

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 Class ) {
            list.add(iterator.next())
        }       
    }
    return list;
}

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

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