[英]How to load and use one more than .class file?
我在这个文件夹中有一个文件夹我有 4 个 .class 文件。我想在我的主程序中加载这个文件并调用方法 .for 一个 .class 文件我喜欢这样:
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");
对于调用我喜欢的方法:
Object obj = clazz.newInstance();
System.out.println(""+obj.getClass().
getMethod("echo",String.class).invoke(obj, "Saeed"));
现在我在文件夹中多了一个 .class 。如何加载和调用它们的方法? 谁能帮我?
您可以使用PathMatcher ,这是一个示例:
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;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.