0

We here (two small teams) are writing an Android library (OpenGL ES 3.1 based graphics effects library, but that's irrelevant to the question). One team writes the Core part (this code ends up in the (*.library.core package) , while another writes the individual effects (each effect is a single .java file in *.library.effects package + some shader code).

Currently the development works like this: each time a new effect gets written (lets say the class that implements it is called EffectBlahBlah), the Core team has to go over their code and, in one place, add a call to a static method EffectBlahBlah.init(), in another place - a call to another static method EffectBlahBlah.getUniforms(), etc etc. There are AFAIK 7 different places where we have to add 7 different calls to certain (static and non-static) methods from the new effect.

Now - having to add 7 lines of code is not the end of the world; however (especially in light of the fact that we are hoping to open the development of the effect part to outside programmers) we are hoping to automatize this in the following way:

  1. have the Core scan the *.library.effect package and come up with a list of all Effect classes that are there (we know how to do this)
  2. in each of those 7 places in our code, automatically call the appropriate method for each discovered class.

Now, if not for the static methods (which have to be there) I'd know how to do this: have all Effects extend an abstract class (lets say 'BaseEffect') which declares the 7 methods abstract, in each of the 7 places instantiate each effect in a loop using Class.forName(), cast it to a BaseEffect and call the appropriate method.

However Java does not allow abstract methods to be static. What do you recommend then?

Leszek
  • 1,181
  • 1
  • 10
  • 21
  • 1
    There are several answers to [this related question](http://stackoverflow.com/questions/370962/why-cant-static-methods-be-abstract-in-java) that are most insightful. – Bob Kaufman Jan 05 '15 at 16:56

1 Answers1

1

You can use reflection for this. A possible sequence of calls is roughly:

  1. Use Class.forName(name) to get the Class instance describing your class.
  2. Call getMethods() on the Class instance to get the list of methods (or getMethod() to directly get a method, if you can figure out how to use it).
  3. For the entries in the returned list of Method instances, use getModifiers() to check if it's static, and getName() to identify a specific method.
  4. Once you found the desired Method instance, call the invoke() method on it to call the method. For static methods, you can use null for the receiver (first argument).
Reto Koradi
  • 53,228
  • 8
  • 93
  • 133