I have a class library, that i didn't write, which defines several classes and subclasses, which have static methods. A very much stripped down example:
public class Vehicle {
static String getName() { return "unknown"; }
}
public class Car extends Vehicle {
static String getName() { return "car"; }
}
public class Train extends Vehicle {
static String getName() { return "train"; }
}
Now, i have an object, which is a Vehicle, may be a Car or a Train, and want to call it's getName() function. Again, very much stripped down:
public class SMCTest {
public static void main(String[] args) {
Vehicle vehicle=new Car();
System.out.println(vehicle.getName());
}
}
This prints "unknown", not "car", as the JVM doesn't need, or use, the object to call a static method, it just uses the class.
If that was my code, i'd rewrite vehicle library to use singletons, and non-static methods, but as it isn't my code, i'd rather not touch it.
Is there any way to call the static method of the "real" class of the object, preferable without using reflection? If it helps, i could change the vehicle
in the above example to a Class <? extends Vehicle>
variable and use that, but i don't see how that helps me to avoid reflection.