从字符串加载类 [英] Loading a Class from a String

查看:121
本文介绍了从字符串加载类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过String的值来实例化一个类。我找到了几个教程,展示了这样做的几种方法。该类必须从某个接口继承, ImplementMe ,它有一个名为 runMe()的特殊方法。所以这就是我的尝试:

I want to instantiate a class by the value of a String. I found several tutorials that show several methods for doing this. The class MUST inherit from a certain interface, ImplementMe which has a special method called runMe(). So here's what I tried:

ImplmentMe a =
   (ImplementMe) ImplementMe.class
                   .getClassLoader()
                   .loadClass("my.package.IImplementedYou")
                   .newInstance();
a.runMe();

它有效,但它太难看了。我至少预计不需要演员。请告诉我有更好的方法。

It works, but it's so ugly. I at least expected not needing a cast. Please tell me there is a better way.

推荐答案

不,没有更好的方法(按设计)。你不应该这样做,Java被设计为一种类型安全的语言。但是,我可以理解你有时需要做这样的事情,为此你可以创建一个像这样的库函数:

No, there is no better way (by design). You are not supposed to do this, Java is designed as a type-safe language. However, I can understand that you sometimes need to do things like this, and for that purposes you can create a library function like this:

public <T> T instantiate(final String className, final Class<T> type){
    try{
        return type.cast(Class.forName(className).newInstance());
    } catch(InstantiationException
          | IllegalAccessException
          | ClassNotFoundException e){
        throw new IllegalStateException(e);
    }
}

现在您的客户端代码至少可以调用此方法cast:

Now your client code can at least call this method without casting:

MyInterface thingy =
    instantiate("com.foo.bar.MyInterfaceImpl", MyInterface.class);

这篇关于从字符串加载类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆