繁体   English   中英

使用Java Reflection加载接口

[英]Using Java Reflection to load Interfaces

有人可以指导我这个。 我有一个类加载器,我可以使用Java反射加载一个类。 但是,无论如何我可以将我的对象转换为界面吗? 我知道有一个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;
}

我唯一可以看到你可能在这里做错的是使用系统类加载器。 很有可能它无法看到您的实现类。

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;
}

对于我来说,强烈建议使用ServiceLoader

看起来你错过了一个对象实例化。

myClassLoader.loadClass("entityclasses.Books") 返回的实例IBorrowable ,但类对象的实例,是指书籍。 您需要使用newInstance()方法创建已加载类的实例

这是固定版本(假设, 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