反射 – 获取 List 的大小

huangapple go评论59阅读模式
英文:

Reflection - Get the size of List<SomeClass>

问题

使用反射帮助我处理反射。有一个 SuperClass 类和一个 SomeClass 类:

public class SuperClass {
    private List<SomeClass> listClass;
    
    public SuperClass(){
        this.listClass = new ArrayList<>();
    }

    // ... 获取器和设置器 listClass
}

public class SomeClass {}

我如何使用反射来获取 SuperClasslistClass 属性的大小?最好是通过调用 getListClass 方法。

英文:

Help me deal with reflection. There is a SuperClass class and a SomeClass:

public class SuperClass {
    private List&lt;SomeClass&gt; listClass;
    
    public SuperClass(){
        this.listClass = new ArrayList&lt;&gt;();
    }

    // ... getter and setter listClass
}

public class SomeClass {}

How can I use reflection to get the size of the listClass property of the SuperClass ? Preferably by calling the getListClass method.

答案1

得分: 1

如果您不确定它是一个列表还是一个集合,可以使用迭代器。

Class<?> objectClass = listClass.getClass();
if (Collection.class.isAssignableFrom(objectClass)) {
    int size = ((Collection<?>) listClass).size();
}

您也可以通过反射调用size()方法,但没有充分的理由这么做。

try {
    int size = (int) listClass.getClass().getMethod("size").invoke(listClass);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    // 做一些处理
}

如果可以的话,您应该直接调用:

listClass.size();
英文:

If you don't know that it's a List or just a collection, you can use an Iterator.

Class&lt;?&gt; objectClass = listClass.getClass(); 
if (Collection.class.isAssignableFrom(objectClass)) {
    int size = ((Collection&lt;?&gt;) listClass).size();
}

You could also call the size() method via reflection, but there is no good reason to do it.

try {
    int size = (int) listClass.getClass().getMethod(&quot;size&quot;).invoke(listClass);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
    // do something
}

If you can, you should just call:

listClass.size();

huangapple
  • 本文由 发表于 2020年10月7日 13:37:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/64237820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定