Re: Extracting Class names in Abstract classes with Generics.
Ian Wilson wrote:
Now that I've pondered what you and Daniel have said, I suspect that
Erasure really prevents me doing what I want in Foo's constructor.
Kind of. Unless you have
public class Foo<E> {
private final string name;
public Foo(Class<? extends E> fooClass) {
name = fooClass.getSimpleName();
}
}
There basically isn't any way to get access to information about
Generics by using simple reflection, unless you have an object to
reflect upon.
I doubt there's much of an efficiency gain either but I first learned
programming with Fortran and it was drilled into me that I should avoid
calling functions more often than strictly necessary. Old habits are
hard to break.
That is a very bad habit, and will lead you down the road of bad design
time and time again. Function calls are considered neglagible on
todays modern systems. And in any case, you should always strive for a
easy-to-understand design first, and then optimize where a profiler
tells you to.
I think the best I can do is declare String className in abstract class
Foo and then assign it in my concrete subclasses Zap and Zog. In reality
I have dozens of such subclasses.
Why subclass? It seems like instead you could just have a String
parameter, instead of automating the name...
public class Foo<E> {
private final String name;
public Foo(String name) {
this.name = name;
}
}
That seems like the easiest way to me.
P.P.S. My AuditLog.memo() call is actually used like this ...
void fooFar(E o) {
AuditLog.memo("objectname", "action", o.toString());
}
Maybe I can change this to pass o and then maybe I can hide
o.getClass().getSimpleName in AuditLog.memo() somehow.
That seems like another good approach. If audit log has the same basic
format all over, why not let AuditLog handle that format?
The best advice I can give you right now is to not over-engineer this.
Do something that works and simple. Its the K.I.S.S. principal - Keep
It Simple Stupid. Once you've gotten something that works, refactor it
so that it works the same way, but has the balance you need between
good design, ease of understanding, and speed.
HTH
- Daniel.