开发者

Getting the names of all Java classes declared in a package

开发者 https://www.devze.com 2023-01-25 03:03 出处:网络
I\'m writing a functionality where it would be helpful t开发者_如何学Goo get the classes inside a certain package of my program. Also, I only want the classes that subclass a certain class.

I'm writing a functionality where it would be helpful t开发者_如何学Goo get the classes inside a certain package of my program. Also, I only want the classes that subclass a certain class.

I need the classes in order to call static methods on them.

Is there an automatic way to do this? If so, is it slow?

In case I was not clear, what I want is something like this:

ArrayList<Class<? extends MySuperClass>> classes = ;

classes.add(MyClass.class); 
classes.add(MyClass2.class); 

Instead of having to call add for each class, I would like to automatically get that class list.

The number of classes is small, so I would not mind declaring them manually if the automatic trick would be slow - this app is for a mobile platform.

In either way, I would also like to know how to call the static method for each method in the ArrayList:

  // error The method nameOfStaticMethod is undefined for the type Class<capture#2-of ? extends MySuperClass>
  classes.get(0).nameOfStaticMethod (); 

Thanks for your comments.


Java doesn't provide this ability. There is no introspection at the package level. The classes could be records in a database, or on the other side of a network connection. There's no requirement for them to be stored and organized so as to facilitate enumerating them by package.

You could make a custom class loader and API to provide a method of listing the class names.


I too would like to list all classes in a package but so far the methods of doing this is pretty bad:

  • Like JOTN suggested - needs file access - not if it is a jar
  • Listing a JAR entries - well, also needs the jar file

Quoting a older SO question:

It isn't possible to query a Package for it's Classes (or even its subpackages). http://forums.sun.com/thread.jspa?threadID=341935&start=0&tstart=0 contains a very good discussion about why this is problematic, as well as a handful of solutions to your problem.

Anyways, here is how you invoke static methods on the class:

Method m = Integer.class.getMethod("toString", Integer.TYPE);
System.out.println(m.invoke(null, 123));
0

精彩评论

暂无评论...
验证码 换一张
取 消