[英]Loading Java classes where package is not known in advance
I have been using the below code to load the classes where I knew the package to load. 我一直在使用下面的代码来加载我知道要加载的包的类。
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
Class<?> myClass = classLoader.loadClass(classNameToBeLoaded);
There is now change in the folder/package structure. 现在,文件夹/包结构发生了变化。
The variable classNameToBeLoaded
can be from any package which I can't know in advance as the class name comes from an user provided Excel sheet. 变量classNameToBeLoaded
可以来自任何我不知道的包,因为类名来自用户提供的Excel工作表。
For example the value of classNameToBeLoaded can be "Utils", "FileValidation" etc as read from Excel file. 例如,从Excel文件读取的classNameToBeLoaded的值可以是“ Utils”,“ FileValidation”等。
This class can be from different packages like "com.iyaffle.utils" or like "com.testing.validation" or anything so. 此类可以来自不同的程序包,例如“ com.iyaffle.utils”或“ com.testing.validation”或其他任何类。
How can I make the class to be loaded automatically when we don't know the package name? 当我们不知道包名称时,如何使该类自动加载?
Other similar thread which does not have concrete answers: 其他没有具体答案的类似线程:
You do need to know the fully qualified name to load the classes, there are lots of classes that have the same class name, and the only thing that keeps them distinct is the package name. 您确实需要知道完全限定的名称才能加载类,很多类具有相同的类名称,唯一使它们与众不同的是程序包名称。
A good example is the following: 以下是一个很好的示例:
If the classes do not have common methods you need to call you can just load them like you are doing now, but adding on the package name. 如果这些类没有通用方法,则可以像现在一样加载它们,然后添加程序包名称。
The safest way to call common methods is to have a static interface or abstract class that all your dynamic classes extend, so that you can then treat the dynamically loaded class instances as instances that implement the common methods. 调用通用方法的最安全方法是拥有一个静态接口或所有动态类都可以扩展的抽象类,以便将动态加载的类实例视为实现通用方法的实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.