How do I read all classes from a Java package in t

2020-01-23 03:30发布

I need to read classes contained in a Java package. Those classes are in classpath. I need to do this task from a Java program directly. Do you know a simple way to do?

List<Class> classes = readClassesFrom("my.package")

17条回答
smile是对你的礼貌
2楼-- · 2020-01-23 04:23

Spring has implemented an excellent classpath search function in the PathMatchingResourcePatternResolver. If you use the classpath*: prefix, you can find all the resources, including classes in a given hierarchy, and even filter them if you want. Then you can use the children of AbstractTypeHierarchyTraversingFilter, AnnotationTypeFilter and AssignableTypeFilter to filter those resources either on class level annotations or on interfaces they implement.

查看更多
神经病院院长
3楼-- · 2020-01-23 04:24

use dependency maven:

groupId: net.sf.extcos
artifactId: extcos
version: 0.4b

then use this code :

ComponentScanner scanner = new ComponentScanner();
        Set classes = scanner.getClasses(new ComponentQuery() {
            @Override
            protected void query() {
                select().from("com.leyton").returning(allExtending(DynamicForm.class));
            }
        });
查看更多
放我归山
4楼-- · 2020-01-23 04:24

Brent - the reason the association is one way has to do with the fact that any class on any component of your CLASSPATH can declare itself in any package (except for java/javax). Thus there just is no mapping of ALL the classes in a given "package" because nobody knows nor can know. You could update a jar file tomorrow and remove or add classes. It's like trying to get a list of all people named John/Jon/Johan in all the countries of the world - none of us is omniscient therefore none of us will ever have the correct answer.

查看更多
祖国的老花朵
5楼-- · 2020-01-23 04:25

I happen to have implemented it, and it works in most cases. Since it is long, I put it in a file here.

The idea is to find the location of the class source file which is available in most cases (a known exception are JVM class files -- as far as I've tested). If the code is in a directory, scan through all files and only spot class files. If the code is in a JAR file, scan all entries.

This method can only be used when:

  1. You have a class that is in the same package you want to discover, This class is called a SeedClass. For example, if you want to list all classes in 'java.io', the seed class may be java.io.File.

  2. Your classes are in a directory or in a JAR file it has source file information (not source code file, but just source file). As far as I've tried, it work almost 100% except the JVM class (those classes come with the JVM).

  3. Your program must have permission to access ProtectionDomain of those classes. If your program is loaded locally, there should be no problem.

I've tested the program only for my regular usage, so it may still have problem.

I hope this helps.

查看更多
地球回转人心会变
6楼-- · 2020-01-23 04:26

Java 1.6.0_24:

public static File[] getPackageContent(String packageName) throws IOException{
    ArrayList<File> list = new ArrayList<File>();
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
                            .getResources(packageName);
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        File dir = new File(url.getFile());
        for (File f : dir.listFiles()) {
            list.add(f);
        }
    }
    return list.toArray(new File[]{});
}

This solution was tested within the EJB environment.

查看更多
地球回转人心会变
7楼-- · 2020-01-23 04:27

Scannotation and Reflections use class path scanning approach:

Reflections reflections = new Reflections("my.package");
Set<Class<? extends Object>> classes = reflections.getSubTypesOf(Object.class);

Another approach is to use Java Pluggable Annotation Processing API to write annotation processor which will collect all annotated classes at compile time and build the index file for runtime use. This mechanism is implemented in ClassIndex library:

Iterable<Class> classes = ClassIndex.getPackageClasses("my.package");
查看更多
登录 后发表回答