【问题标题】:Using Java Reflection to load Interfaces使用 Java 反射加载接口
【发布时间】: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


【解决方案1】:

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

myClassLoader.loadClass("entityclasses.Books") 确实返回IBorrowable 的实例,而是引用书籍的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;
}

【讨论】:

    【解决方案2】:

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

    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

    【讨论】:

      猜你喜欢
      • 2011-10-31
      • 2016-04-16
      • 2016-06-16
      • 2011-10-18
      • 2022-01-19
      • 2011-06-21
      • 2015-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多