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)
5
  • Possible duplicate of java.lang.ClassCastException Commented Mar 14, 2018 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? Commented Mar 14, 2018 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. Commented Mar 15, 2018 at 7: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. Commented Mar 15, 2018 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. Commented Mar 16, 2018 at 11:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.