[英]Get throwable class object from String className
Given a string like com.abc.XYZException
I'd like to get a throwable class that can be resolved from the class path with that string as class name. 给定一个像
com.abc.XYZException
这样的字符串,我想得到一个可抛出的类,可以从类路径中解析该字符串作为类名。
private Class<? extends Throwable> getExceptionClass(String className){
return Class.forName(className);
}
This snippets cant be compiled because Class.forName(className)
returns Class<?>
but Class<? extends Throwable>
这个片段无法编译,因为
Class.forName(className)
返回Class<?>
但是Class<? extends Throwable>
Class<? extends Throwable>
is required. Class<? extends Throwable>
是必需的。 How do I return Class<? extends Throwable>
如何返回
Class<? extends Throwable>
Class<? extends Throwable>
? Class<? extends Throwable>
?
The unchecked cast is unavoidable but you could do things safer by checking that the input is conform before casting it. 未经检查的演员阵容是不可避免的,但你可以通过在投票之前检查输入是否符合来做更安全的事情。
You could indeed use isAssignableFrom()
method of Class
to check that the Class
instance loaded is a subclass of the Throwable
class. 事实上,你可以使用
isAssignableFrom()
的方法Class
来检查Class
加载实例是一个子类Throwable
类。
public Class<? extends Throwable> getExceptionClass(String className) {
try {
Class<?> clazz = Class.forName(className);
if (!Throwable.class.isAssignableFrom(clazz)) {
throw new IllegalArgumentException("error in the provided classname");
}
return (Class<? extends Throwable>) clazz;
} catch (ClassNotFoundException e) {
// handling the exception
}
}
As also suggested in a comment (unchecked cast of the returned class), this should be what you require in order to let it be compiled: 正如评论中所建议的(未经检查的返回类的强制转换),这应该是你需要的,以便让它被编译:
private Class<? extends Throwable> getExceptionClass(String className) throws ClassNotFoundException {
return (Class<? extends Throwable>) Class.forName(className);
}
This should do the trick; 这应该可以解决问题;
private Class<? extends Throwable> getExceptionClass(String className) throws ClassNotFoundException{
return (Class<? extends Throwable>) Class.forName(className);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.