-2

I have a folder in this folder I have 4 .class file .I want load this files in my main program and call the methods .for one .class file I do like so:

File file = new File("/home/saeed/NetBeansProjects/java-test/build/classes");

URI uri = file.toURI();
URL[] urls = new URL[]{uri.toURL()};

ClassLoader classLoader = new URLClassLoader(urls);

Class clazz = classLoader.loadClass("com.test.NewClass");

And for invoke the method I do like so:

Object obj = clazz.newInstance();

System.out.println(""+obj.getClass().
        getMethod("echo",String.class).invoke(obj, "Saeed"));

Now I have one more than .class in the folder .How can I load and invoke their methods? Can anyone help me?

marzie
  • 203
  • 3
  • 11
  • Um...do the same thing three more times? Or better yet, put that directory in your classpath and use them normally? What's the question here exactly? – T.J. Crowder Aug 30 '15 at 07:46
  • How to load 4 .class file from a folder? – marzie Aug 30 '15 at 07:49
  • That question doesn't make any sense. What are you actually trying to do? If you're just trying to use class files in the normal way, you don't use a classloader directly at all. See: https://docs.oracle.com/javase/tutorial/essential/environment/paths.html – T.J. Crowder Aug 30 '15 at 07:55
  • @marzie, we do not understand why you use reflection to load these classes? why not put the folder in classpath? and if you insist on using reflection, the obvious answer is to copy-paste `loadClass` with `clazz1` `clazz2` etc – Sharon Ben Asher Aug 30 '15 at 07:56
  • I insist on using reflection .I know how to load one .class file but in my folder there is 4 .class file .How do I load all of them? – marzie Aug 30 '15 at 07:59
  • possible duplicate of [Can you find all classes in a package using reflection?](http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection) – Limnic Aug 30 '15 at 08:22

1 Answers1

0

You can use PathMatcher, here is an example:

Path startDir = Paths.get("C:\\home");

String pattern = "*.class";

FileSystem fs = FileSystems.getDefault();
final PathMatcher matcher = fs.getPathMatcher("glob:" + pattern);

FileVisitor<Path> matcherVisitor = new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attribs) {
        Path name = file.getFileName();
        if (matcher.matches(name)) {
            // Found a .class file 
            System.out.print(String.format("Found matched file: '%s'.%n", file));
        }
        return FileVisitResult.CONTINUE;
    }
};
Limnic
  • 1,826
  • 1
  • 20
  • 45
Bruno Caceiro
  • 7,035
  • 1
  • 26
  • 45