loading specific class files in java
I have a directory which contains lots of class files. Some of these files begin with the name test_____.class and i want to load only these class files i.e test___.class in another Java program.How can i read only these specific files?? can i use some kind of regular expression开发者_Go百科s?
If your classes are in the class path, you may try to get all the class names and the just load them.
String packageName = "some.name";
File dir = new File("/Path/to/your/classes/some/name");
String [] classes = dir.list( new FilenameFilter(){
public boolean accept( File dir, String name ) {
return name.matches("test.*\\.class");
}
}
for( String name: classes ) {
Class.forName( packageName + name );// load them
}
If they are not, you can load them using URLClassloader
instead.
you can read the directory to get a list of the classes and filter it any way you want. You can then instantiate the classes you want, but of course you have to use some interface, not the class name itself, as the hook to invoke methods of the class.
If you don't want to deal with reading and parsing directories, you could just embed the list of test classes in an applet or command line parameter.
精彩评论