I’m working on my first real project with Java. I’m beginning to get comfortable with the language, although I have more experience with dynamic languages.
I have a class that behave similar to the following:
class Single
{
public void doActionA() {}
public void doActionB() {}
public void doActionC() {}
}
And then I have a SingleList class that acts as a collection of these classes (specifically, it’s for a 2D Sprite library, and the “actions” are all sorts of transformations: rotate, shear, scale, etc). I want to be able to do the following:
class SingleList
{
public void doActionA() {
for (Single s : _innerList) {
s.doActionA();
}
}
... etc ...
}
Is there any way to simply defer a method (or a known list of methods) to each member of the inner list? Any way without having to specifically list each method, then loop through each inner member and apply it manually?
To make things a bit harder, the methods are of varying arity, but are all of return type “void”.
Unfortunately Java does not readily support class creation at runtime, which is what you need: the
SingleListneeds to be automatically updated with the necessary stub methods to match theSingleclass.I can think of the following approaches to this issue:
Use Java reflection:
SingleListclass would not be compatible with theSingleclass interface any more.Use a build system along with some sort of source code generator to automatically create the
SingleList.javafile.SingleListclass loaded in any JVM – or your IDE, for that matter – actually matches the loadedSingleclass.Tackle this issue manually – creating an interface (e.g.
SingleInterface) or a base abstract class for use by both classes should help, since any decent IDE will point out unimplemented methods. Proper class architecture would minimize the duplicated code and your IDE might be able to help with generating the boilerplate parts.Use a bytecode generation library such as Javassist or BCEL to dynamically generate/modify the
SingleListclass on-the-fly.