【发布时间】:2013-03-19 09:43:20
【问题描述】:
有人可以指导我吗?我有一个类加载器,我可以使用 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;
}
【问题讨论】:
-
您需要在转换之前对返回的类调用
newInstance()。这当然假设您在实际类上有一个默认构造函数。 -
@StephenC - 他的异常处理确实很糟糕,但这不是他当前代码的问题。
-
我刚刚意识到。我太累了。
标签: java reflection interface