3

I am trying to create instances of a class in SpringBootApplication using reflection. To achieve the same I am trying to get a 'Class' object using the Class.forName(String ClassName) method but it throws me a ClassCastException with nested ClassNotFoundException. I have a faint idea that Spring Boot has its own classloader and it's not being able to locate my Java file despite it being in the main src folder. Is there any way to fix this?

    public static List<Object> createExcelBeans(List<LinkedList<String>> excelData, List<String> excelFields,
        String className)
        throws NumberFormatException, IllegalAccessException, IllegalArgumentException, InvocationTargetException,
        ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IOException {
    List<Object> pojoList = new LinkedList<Object>();
    /*
     * getting the class instance of the specified name
     */
    Class<?> pojoClass = Class.forName(className);

Stack trace:

java.lang.ClassNotFoundException: ExcelBean
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.Excel.ExcelService.createExcelBeans(ExcelService.java:39)
at com.Excel.ExcelReader.excelReaderService(ExcelReader.java:137)
at com.Excel.ExcelReader.excelToPojo(ExcelReader.java:43)
  • Possible duplicate of [java.lang.ClassCastException](https://stackoverflow.com/questions/3511169/java-lang-classcastexception) – Syed Waqas Bukhary Mar 14 '18 at 15:34
  • Can you post your build file and the full stack trace? Does your Spring Boot jar contain the class you are trying to cast to? – Yserbius Mar 14 '18 at 16:11
  • Both my Spring boot main class and the ExcelBean class reside in src/main/java folder. The program was working fine with a normal java main class but it's not able to find the class now after introducing Spring boot. – Vivek Dehariya Mar 15 '18 at 07:57
  • I don’t see any `ClassCastException`. Besides that, you should know that you have to compile the Java files in your src folder, to use them at runtime. – Holger Mar 15 '18 at 14:14
  • I get ClassCastException when I specify the class name as Packagename.classname, I have the compiled classes in the src folder and as mentioned the code works without using spring boot, it has something to do with spring's classloader. – Vivek Dehariya Mar 16 '18 at 11:27

0 Answers0