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?
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;
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.