如果我有 3 个名为 CPU、GPU、RAM 的类,并且我将这些类存储到一个数组列表中ArrayList<Object> stock = new ArrayList<>()
,您可以使用什么方法来返回存储在某个索引中的类。例如
stock = new ArrayList<>;
stock.add(new CPU());
stock.add(new GPU());
//method to determine which class is in index 0
System.out.println(method);
Output: class packageName.CPU
您可以简单地获取元素 0,然后是类,最后是它的名称。
ArrayList<Object> stock = new ArrayList<>();
class CPU{};
class GPU{};
stock.add(new CPU());
stock.add(new GPU());
System.out.println(stock.get(0).getClass().getName());
输出就是你想要的:
com.example.example.model.CPU
如果您需要所有类,只需在过程中添加一个 foreach:
stock.forEach(i -> {
System.out.println(i.getClass().getName());
});
com.example.example.model.CPU
com.example.example.model.GPU
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句