3

I'm working on a java app that will have a lot of contributions. I want classes in a single package to somehow "self-register" themselves. Currently, we have another classes that simply adds each to a listlike this:

ourlist.add( new SomeClassName() );

This requires that each contributor add a line like this for their addition which I want to avoid. I want to get the application to scan the package, and automatically add each class to the list like above.

I've tried using some class scanning code for packages but the class types weren't playing well with ours and I'm too new to java to fully comprehend the issue.

helion3
  • 34,737
  • 15
  • 57
  • 100
  • try this: http://www.dzone.com/snippets/get-all-classes-within-package – Nir Alfasi Jun 13 '12 at 05:37
  • That's what I tried. It didn't seem to be working because the Class[] type is not the same type of classes we're loading and eclipse keeps complaining that the types didn't match. I tried changing the types of that code to match but then the last line, the classes.add(Class.forName part didn't work. – helion3 Jun 13 '12 at 05:49
  • Interesting question. Unfortunately Java provides no way to share a class-level (aka `static`) behavior. My hunch is that AspectJ might have some solution for this. Have you looked into it? – missingfaktor Jun 13 '12 at 07:25
  • Several points are not clear from your question, you say you want to register classes but in your example you register an instance. So do you want to register one instance, all instances, or just the class? Why do you want to register. Do you have to register at startup or is it enough to register once constructor is called? Do you use something like Spring or Guice? Would the usage of a javaagent be possible? – pgras Jun 13 '12 at 08:31

2 Answers2

0

run time or static ? for run time You may use static block in the classes and place code in side static block to register themselves. like the way JDBC drivers work and register with drivermanager.

sudmong
  • 2,036
  • 13
  • 12
0

Scan the package to get all class name and using Reflection create instance of each to add into list

for(Class claszz: scannedClasses){
 list.add(clazz.newInstance());//default constructor
}
Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438