Artur Peniche
Artur Peniche

Reputation: 479

java.lang.ClassNotFoundException on classloader

The idea of this code is to receive some java files that extends another java file that I've on the server.

At this moment I'm ignoring the obvious security problems but non the less the code is the following:

private boolean isTheFileIamLookingFor(String name,String path,String nameOfFatherClass) {
        System.out.println("NAME IS "+name); //prints correct class name
        System.out.println("PATH IS "+path); //prints correct path
        if(Files.getFileExtension(path).equals("class"))
        {
            try {
                ClassLoader classLoader = this.getClass().getClassLoader();
                Class<?> loadedMyClass = classLoader.loadClass(String.format("%s.class", name));
                Class<?> c[] = loadedMyClass.getInterfaces();
                if(Arrays.asList(c).contains(Class.forName(nameOfFatherClass)))
                {
                    return true;
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return false;

    }

But I'm getting the error

java.lang.ClassNotFoundException: MyClass.class

But the fact is that the file is there. Any thougths about why the class isn't found?

cmd log

Upvotes: 0

Views: 407

Answers (1)

RamPrakash
RamPrakash

Reputation: 1834

import java.util.Arrays; import org.apache.commons.io.FilenameUtils;

public class mytest {

public static void main(String[] args) {
    mytest m = new mytest();
    System.out.println(m.isTheFileIamLookingFor("ArrayList", "java.util.",
            "List"));
}

public boolean isTheFileIamLookingFor(String name, String path,
        String nameOfFatherClass) {
    System.out.println("NAME IS " + name); // prints correct class name
    System.out.println("PATH IS " + path); // prints correct path
    if (!FilenameUtils.getExtension(path).equals("class"))

    {
        try {
            ClassLoader classLoader = this.getClass().getClassLoader();
            System.out.println(String.format("%s.class", name));
            Class<?> loadedMyClass = classLoader.loadClass(path + name);
            Class<?> c[] = loadedMyClass.getInterfaces();
            if (Arrays.asList(c).contains(
                    Class.forName(path + nameOfFatherClass))) {
                return true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    return false;

}

}

Upvotes: 1

Related Questions