1

I need to get method names of a class from a java file in a directory.

   File file=new File("C:/class/");
    try {
      // Convert File to a URL
      URL url = file.toURL();          // file:/c:/class/
      URL[] urls = new URL[]{url};

      // Create a new class loader with the directory
      URLClassLoader loader = new URLClassLoader(urls);

      // Load in the class; Class.childclass should be located in
      // the directory file:/c:/class/
      Class cls = loader.loadClass("Arithmatic.java");
      Method[] methods=cls.getMethods();
      for(Method method:methods){
       System.out.println("Method name:"+method.getName());
      }
  } catch (MalformedURLException e) {
   System.out.println("Exception");
  } catch (ClassNotFoundException e) {
   System.out.println("Class not found exception");
  }

I am getting ClassNotFoundException.

Is this is the correct way of doing?

Can any body suggest the solution please...

2 Answers 2

3

You can't load a .java file as class. You should load a .class file (which means it should be compiled first)

loader.loadClass("Arithmatic", true);

In case you don't have the class in a compiled form, you can compile it at runtime using JavaCompiler

Sign up to request clarification or add additional context in comments.

Comments

2

Try

Class.forName("Arithmatic", true, loader)

instead of

loader.loadClass("Arithmatic.java")

Comments

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.