public class InpackageTest {
private static Class[] getClasses(String packageName)
throws ClassNotFoundException, IOException {
File classpathLocation =null;
System.out.println("package name - > "+packageName);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
System.out.println("path --- name - > "+path);
Enumeration resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while (resources.hasMoreElements()) {
URL resource = (URL) resources.nextElement();
classpathLocation = new File(resource.getFile());
System.err.println("resource.getFile()- > "+resource.getFile());
dirs.add(new File(resource.getFile()));
}
ArrayList classes = new ArrayList();
System.out.println("dirs- > "+dirs.size());
for (File directory : dirs) {
classes.addAll(findClasses(classpathLocation, packageName));
}
return (Class[]) classes.toArray(new Class[classes.size()]);
}
private static List findClasses(File directory, String packageName) throws ClassNotFoundException {
List classes = new ArrayList();
System.out.println("directory > "+directory.getName()+" -- > pacakge- > "+packageName);
if (directory.exists()) {
System.out.println("Dir exist - > "+directory.exists());
return classes;
}
System.out.println("directory- > "+directory.getAbsolutePath());
File[] files = directory.listFiles();
for (File file : files) {
System.out.println("file name - > "+file.getName());
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
return classes;
}
public static void main(String[] args) throws ClassNotFoundException {
List<String> results = new ArrayList<String>();
List<String> listOfClasses_Name = new ArrayList<String>();
List<Field> Fields = new ArrayList<>();
try {
Class [] c =InpackageTest.getClasses("com.compensation.content");
System.out.println(c.getClass().getName().toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here i have try to get the field under the package in same project.package name given,i cant get the list of files under the folder. Question becomes : how can i get the java files under some specific location in my system using java reflection(Moto: need to get all the fields under the class which is reside under some folder.)
Aucun commentaire:
Enregistrer un commentaire