使用Java反射来加载接口



谁能指点一下我吗?我有一个类加载器,我可以使用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;
}

看起来您缺少一个对象实例化。

myClassLoader.loadClass("entityclasses.Books") 不是返回IBorrowable的实例,而是一个指向Books的Class对象的实例。您需要使用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;
}

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

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对我来说是强烈推荐的。

最新更新