In one of my projects I use Guava to get the class name from command line and then call appropriate constructor. User runs the .bat file with something like:
java -jar MyClass.jar OtherClass
OtherClass is located at some package like mypackage.otherpackage. I want to call it's constructor in the code. To find the constructor, I use Guava:
Constructor classConstructor = null;
Set<ClassInfo> classInfos = ClassPath.from(MyClass.class.getClassLoader()).getTopLevelClassesRecursive("mypackage");
List<String> packageNames = classInfos.stream().map(classInfo -> classInfo.getPackageName()).distinct().collect(Collectors.toList());
for (String p : packageNames) {
try {
classConstructor = Class.forName(p + "." + args[0]).getConstructor(String.class);
} catch (ClassNotFoundException ex) {
}
if (classConstructor != null)
break;
}
And it works just perfect on one computer but doesn't work at all on another one because ClassPath.from(MyClass.class.getClassLoader()).getTopLevelClassesRecursive("mypackage");
returns 0 elements. I don't understand why. The code on both computers is equal, packages are equal, classes too.