I need to use Java's Class.forName("") to load one of my classes. Problem is that I need to load the class by only specifying the class name and NOT the fully qualified class name.
我需要使用Java的Class.forName(“”)来加载我的一个类。问题是我需要通过仅指定类名而不是完全限定的类名来加载类。
-
For example this works but doesn't fit my requirements:
例如,这有效,但不符合我的要求:
Class.forName("reflection.Person");
的Class.forName( “reflection.Person”);
-
And this is what I need but is not working:
这就是我需要的但是不起作用:
Class.forName("Person");
的Class.forName( “人”);
Anyone knows how to get #2 working? I just need to use the simple class name. Any 3rd party tools that will walk through my folder structure to check if the class exists? This will be deployed as an executable JAR.
谁知道如何让#2工作?我只需要使用简单的类名。任何第三方工具将遍历我的文件夹结构以检查该类是否存在?这将部署为可执行JAR。
Thanks in advance.
提前致谢。
2 个解决方案
#1
4
You should get all classes on the classpath, iterate them and see which one has a simple name that is equal to the desired one. Then do Class.forName(..)
with the fully-qualified name. Note that the same name can be used in multiple packages.
您应该获取类路径上的所有类,迭代它们并查看哪个类具有与所需类型相同的简单名称。然后使用完全限定名称执行Class.forName(..)。请注意,可以在多个包中使用相同的名称。
You'd better look for classes implementing an interface or annotated with a specific annotation. Relying on the simple name can be really tricky, especially if your classpath grows.
您最好寻找实现接口的类或使用特定注释进行注释的类。依赖简单的名称可能非常棘手,尤其是在类路径增长的情况下。
#2
1
You need to understand that the meaning of a class name like "Person" depends on where it occurs in the source code. It is a convenience of the Java compiler to not require fully qualified class names everywhere. But at runtime, in byte code, all class names are fully qualified.
您需要了解类名称“Person”的含义取决于它在源代码中的位置。 Java编译器的一个便利是不需要在任何地方使用完全限定的类名。但在运行时,在字节代码中,所有类名都是完全限定的。
#1
4
You should get all classes on the classpath, iterate them and see which one has a simple name that is equal to the desired one. Then do Class.forName(..)
with the fully-qualified name. Note that the same name can be used in multiple packages.
您应该获取类路径上的所有类,迭代它们并查看哪个类具有与所需类型相同的简单名称。然后使用完全限定名称执行Class.forName(..)。请注意,可以在多个包中使用相同的名称。
You'd better look for classes implementing an interface or annotated with a specific annotation. Relying on the simple name can be really tricky, especially if your classpath grows.
您最好寻找实现接口的类或使用特定注释进行注释的类。依赖简单的名称可能非常棘手,尤其是在类路径增长的情况下。
#2
1
You need to understand that the meaning of a class name like "Person" depends on where it occurs in the source code. It is a convenience of the Java compiler to not require fully qualified class names everywhere. But at runtime, in byte code, all class names are fully qualified.
您需要了解类名称“Person”的含义取决于它在源代码中的位置。 Java编译器的一个便利是不需要在任何地方使用完全限定的类名。但在运行时,在字节代码中,所有类名都是完全限定的。