简体   繁体   English

使用Java Reflection加载接口

[英]Using Java Reflection to load Interfaces

Can someone please guide me on this. 有人可以指导我这个。 I have a class loader which I could load a class using Java reflection. 我有一个类加载器,我可以使用Java反射加载一个类。 However, is there anyway I can cast my object to an interface? 但是,无论如何我可以将我的对象转换为界面吗? I understand that there is a ServiceLoader but I read it is highly not recommended. 我知道有一个ServiceLoader但我读它是非常不推荐的。

//returns a class which implements IBorrowable
public static IBorrowable getBorrowable1()  
{
    IBorrowable a;  //an interface
     try
        {
            ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
            a = (IBorrowable) myClassLoader.loadClass("entityclasses.Books");

        }
    catch (Exception e ){
        System.out.println("error");
    }
    return null;
}

The only thing I can see that you might be doing wrong here is using the system classloader. 我唯一可以看到你可能在这里做错的是使用系统类加载器。 The chances are it won't be able to see your implementation class. 很有可能它无法看到您的实现类。

public static IBorrowable getBorrowable1()  //returns a class which implements IBorrowable
{
    IBorrowable a;  //an interface
     try
        {
            a = (IBorrowable) Class.forName("entityclasses.Books");
        }
    catch (Exception e ){
        System.out.println("error");
    }
    return a;
}

As an aside ServiceLoader for me is highly recommended. 对于我来说,强烈建议使用ServiceLoader

Looks like you are missing an object instantiation. 看起来你错过了一个对象实例化。

myClassLoader.loadClass("entityclasses.Books") does not return an instance of IBorrowable , but an instance of Class object, that refers to Books. myClassLoader.loadClass("entityclasses.Books") 返回的实例IBorrowable ,但类对象的实例,是指书籍。 You need to create an instance of the loaded class using newInstance() method 您需要使用newInstance()方法创建已加载类的实例

Here is fixed version (assuming, Books has default constructor) 这是固定版本(假设, Books有默认构造函数)

public static IBorrowable getBorrowable1()  //returns a class which implements IBorrowable
{
     try {
        ClassLoader myClassLoader = ClassLoader.getSystemClassLoader();
        Class<IBorrowable> clazz = (IBorrowable) myClassLoader.loadClass("entityclasses.Books");
        return clazz.newInstance();
    } catch (Exception e) {
        System.out.println("error");
    }
    return null;
}

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

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