First of all hello everyone and sory for my bad english :P
I have an problem with Class.forName method. If i use Class.forName with parameter as Example.class , it throws ClassNotFoundException. Then i try without class prefix for example org.example.Example and it worked. How can i solve this problem ?
My basic code and stack trace:
public class Main {
public static void main(String[] args) throws ClassNotFoundException {
Class clazz = Class.forName(String.valueOf(EventPublisherContext.class));
System.out.println(clazz.getSimpleName());
}
Exception in thread "main" java.lang.ClassNotFoundException: class org.cqs.impl.EventPublisherContext
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:390)
at java.base/java.lang.Class.forName(Class.java:381)
at org.cqs.impl.Main.main(Main.java:10)
Actually i solved this problem with basic method, in below:
public static Class getClass(Class clazz) throws ClassNotFoundException {
List<String> classString = new ArrayList<>();
String[] g = clazz.toString().split(" ");
Arrays.stream(g).forEach(val -> {
classString.add(val);
});
classString.remove(0);
return Class.forName(String.join("", classString));
}
Then i got my expect value:
public static void main(String[] args) throws ClassNotFoundException {
Class clazz = getClass(EventPublisherContext.class);
System.out.println(clazz.getSimpleName());
//print EventPublisherContext
How can i solve this problem without any additional method if it is not impossible.
Aucun commentaire:
Enregistrer un commentaire