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 SingleList
needs to be automatically updated with the necessary stub methods to match the Single
class.
I can think of the following approaches to this issue:
Use Java reflection:
SingleList
class would not be compatible with the Single
class interface any more.Use a build system along with some sort of source code generator to automatically create the SingleList.java
file.
SingleList
class loaded in any JVM - or your IDE, for that matter - actually matches the loaded Single
class.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 SingleList
class on-the-fly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With