English 中文(简体)
Typesafe for Name类加载
原标题:Typesafe forName class loading

当结果是泛型类型时,如何调用Class.forName()?通常我可以使用asSubclass(),但这里我看到的唯一方法是强制转换,它有点突出&;当其他所有东西都用泛型很好地键入时,我很恼火。

场景大致如下:

有一个.jar,它有一个入口点主类,该类有一个<code>main()</code>。它有一个类名选项(还有一些其他选项,在这里无关紧要)。给定的类实现了<code>可调用<;整数>。这个类被加载、初始化&;启动。

以下是我需要的示例:

Class<? extends Callable<Integer>> clazz = (Class<? extends Callable<Integer>>) Class.forName(options.valueOf(className)).asSubclass(Callable.class);

有没有办法去掉那个演员阵容?

使用SE6。

最佳回答

首先,您可能想要一个完整的通用

Class<Callable<Integer>> classCI = ...;

那么java类型的系统对于

Class<? extends Callable<Integer>> clazz =     
    Class.forName(options.valueOf(className))
    .asSubclass(classCI);

如何获得classCI?我们可以通过取消选中的演员阵容来作弊

Class<Callable<Integer>> classCI = (Class<Callable<Integer>>)Callable.class;

这本质上是不安全的。必须有外力来确保className真的是Callable<;整数>。例如,如果它是一个<code>可调用<;字符串>时,该程序运行所有的强制转换都没有任何问题,而且只有在调用Integer call()时才会崩溃,错误消息会非常误导。

如果不能静态分析强制转换以使其成功,也没关系:

Object o = ...;
String s1 = (String)o; // may fail, no javac warning
String s2 = String.class.cast(o); // may fail, no javac warning

只要在运行时强制转换失败时立即引发异常。

为了确保类型安全,我们必须主动检查className的泛型类型

@SuppressWarning( "unchecked" )
Class<? Callable<Integer>> getClass(String className)
{
    Class clazz = Class.forName(className);
    via reflection, check generic super interfaces of clazz
    if there s no Callable<Integer> super interface
        throw "className is not a Callable<Integer>"

    // we have *checked*, the following cast is safe
    return (Class<? Callable<Integer>>)clazz; 
}

我们有理由在这里取消“unchecked”,因为实现会检查,以确保如果className并没有真正表示实现Callable<;整数>,它立即在那里抛出一个异常。我们的演员阵容经过“检查”,程序是类型安全的。

问题回答

暂无回答




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签