如何从不完整的类名中获取实例化对象?
世界!我需要从其类的名称实例化一个对象。我知道可以这样做,这样的
MyObject myObject = null;
try {
Constructor constructor = Class.forName( "fully.qualified.class.name" ).getConstructor(); // Get the constructor without parameters
myObject = (MyObject) constructor.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
问题是我的班级名称不完全限定。有没有办法只知道简称就得到完整的名字?
world! I need to instantiate an Object from the name of its Class. I know that it is possible to do it, this way
MyObject myObject = null;
try {
Constructor constructor = Class.forName( "fully.qualified.class.name" ).getConstructor(); // Get the constructor without parameters
myObject = (MyObject) constructor.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
The problem is that the name of my class is not fully qualified. Is there a way to get the complete name by only knowing the short name?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Package.getPackages()
调用将为您提供当前类 ClassLoader 及其祖先已知的每个包。警告:这会很昂贵,因为您会重复抛出和捕获异常。可以通过以下测试来加快速度:
在调用
Class.forName(...)
或等效方法之前。The
Package.getPackages()
call will give you every package known to the current classes ClassLoader and its ancestors.Warning: this will be expensive because you are repeatedly throwing and catching exceptions. It may be possible to speed it up by testing:
before calling
Class.forName(...)
or the equivalent.重复尝试此操作以获取包搜索路径。 ;)
Try this repeatedly for a package search path. ;)