繁体   English   中英

使用反射返回一个实现接口的类

[英]return a class implementing an interface using reflections

我正在使用反射来查找实现 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”字符串作为参数,该方法将返回一个狗类。

是否有可能做到这一点,关于如何实现上面框中的逻辑的任何想法?

所以这基本上归结为如何创建一个具有代表该类型的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方法。 例如,对于具有一个带一个int参数的构造函数的Integer类,以下将打印“5”:

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

暂无
暂无

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

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