【问题标题】:return a class implementing an interface using reflections返回使用反射实现接口的类
【发布时间】:2021-09-26 13:37:42
【问题描述】:

我正在使用反射来查找所有实现 IAnimal 接口的类。 但是如何使用以下代码中设置的动物返回一个类实例:

Reflections reflections = new Reflections(IAnimal.class);    
Set<Class<? extends IAnimal>> animals= reflections.getSubTypesOf(IAnimal.class);

我有 3 个类实现 IAnimal 接口 Dog、Cat、Duck。我想应用这个逻辑,但我不知道该怎么做。

    method findAnimal(String animalName){

        for (Iterator<Class<? extends Operations>> it = animals.iterator(); it.hasNext(); ) {
            String classname=it.Name;
            if (classname.eqauls(animalName)){
               System.out.println("found");
                return new class(); }
        }}

如果与传递的字符串匹配,我希望 findAnimal 方法返回一个类实例。即,如果我将“Dog”字符串作为参数传递,该方法将返回一个狗类。

是否可以这样做,关于如何实现上面框中的逻辑的任何想法?

【问题讨论】:

  • "我怎么称呼...类"你不知道。
  • @Michael,对不起,我的意思是返回一个类实例
  • 你必须使用反射?没有反射有更简单的方法

标签: java class oop reflection reflections


【解决方案1】:

所以这基本上归结为如何创建一个具有代表该类型的java.lang.Class 的实例?

您可以使用以下代码创建实例:

Class<?> cl = it.next();
... if condition, you decide to create the instance of cl

IDog object= cl.getDeclaredConstructor().newInstance(); // will actuall be a Dog, Cat or whatever you've decided to create

注意,您假设存在默认构造函数(没有参数的构造函数)。这种假设是必要的,因为您必须知道如何创建您感兴趣的类的对象。

如果你知道,你有构造函数接受一些特定参数(特定类型),你可以将参数类型传递给getDeclaredConstructor 方法。例如,对于类Integer,它的构造函数带有一个int 参数,以下将打印“5”:

Integer i = Integer.class.getDeclaredConstructor(int.class).newInstance(5);
System.out.println(i);

【讨论】:

  • 非常感谢马克的帮助和解释,非常感谢。
猜你喜欢
  • 2015-10-21
  • 2011-10-31
  • 2023-03-03
  • 2013-01-18
  • 2010-12-03
  • 1970-01-01
  • 2010-09-09
  • 2013-07-22
  • 1970-01-01
相关资源
最近更新 更多