6

I'm writing a functionality where it would be helpful to 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.

MyName
  • 2,136
  • 5
  • 26
  • 37

2 Answers2

2

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.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
bmargulies
  • 97,814
  • 39
  • 186
  • 310
  • Could yo provide a description why this ability is not included / would be hard to implement? – Maarten Bodewes Oct 02 '15 at 10:47
  • The classes may 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. – bmargulies Oct 02 '15 at 10:49
  • Frummeled your comment into the answer ("frummeled" is Dutch slang, which I think should be used in English as well, meaning: made it fit somehow, after a lot of "frummeling"). – Maarten Bodewes Oct 02 '15 at 10:53
1

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));
Community
  • 1
  • 1
dacwe
  • 43,066
  • 12
  • 116
  • 140