Access static method on generic class - java

I'd like to access a static method on a class, but have that class passed in a generic.
I've done the following:
class Base{
public static String getStaticName(){
return "Base";
}
}
class Child extends Base{
public static String getStaticName(){
return "Child";
}
}
class StaticAccessor{
public static <T extends Base>String getName(Class<T> clazz){
return T.getStaticName();
}
}
StaticAccessor.getName() // --> "Base"
This will return "Base" but what i'd like is "Child" anybody a suggestion without reflections?

You can't do that without reflection, because the type T is erased at runtime (meaning it will be reduced to its lower bound, which is Base).
Since you do have access to a Class<T> you can do it with reflection, however:
return (String) clazz.getMethod("getStaticName").invoke(null);
Note that I'd consider such code to be code smell and that it is pretty fragile. Could you tell us why you need that?

If it is OK for you to pass an object instance rather than Class in your static accessor, then, there is a simple and elegant solution:
public class Test {
static class Base {
public static String getStaticName() { return "Base"; }
public String myOverridable() { return Base.getStaticName(); };
}
static class Child extends Base {
public static String getStaticName() { return "Child"; }
#Override
public String myOverridable() { return Child.getStaticName(); };
}
static class StaticAccessor {
public static <T extends Base>String getName(T instance) {
return instance.myOverridable();
}
}
public static void main(String[] args) {
Base b = new Base();
Child c = new Child();
System.out.println(StaticAccessor.getName(b));
System.out.println(StaticAccessor.getName(c));
}
}
The output is:
Base
Child

I don't believe you can do this without reflection.
It appears you should be doing is not using static methods. You are using inheritance but static methods do not follow inheritance rules.

Related

How use static extended variables in Java?

We have base class as follow:
public class Base {
protected static string rule = "test_1";
public static getRule(){
/* get rule value from origin class*/
}
}
We have some classes that extend from base class. For example:
public class Derived extends Base {
static {
rule = "test_2";
}
}
Now we wants to get rule variable, but in some conditions:
If user call Derived.getRule(), it return test_2,
If in derived class rule variable not init, it returned test_1,
I don't want to override getRule in all subclasses for answer the question.
What do I do?
The problem is, that once the Derived class is used (initialized), Base.rule is changed, and everywhere now test_2 is returned, irrespective of the actual class.
So the technique has to be done without static (in that form). There is a categorical, class level value.
public class Base {
private static final String BASE_RULE = "test_1";
public String getRule() {
return BASE_RULE;
}
}
public class Derived extends Base {
private static final String DERIVED_RULE = "test_2";
#Override
public String getRule() {
return DERIVED_RULE;
}
}
Alternatively you can use marker interfaces - which are not mutual-exclusive however, hence not for some getCategory().
public class Base implements Test1Category {
}
public class Derived extends Base implements Test2Category { ... }
if (base instanceof Test2Category) { ... }

Can i call a static java method when all i have is an object?

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.
preferable without using reflection?
Drop that requirement, and:
vehicle.getClass().getMethod("getName").invoke(null);
would solve the problem as asked.
(However, you should fix the code.)
There is no need for reflection if you know all of the classes involved. With java 8 (create the necessary interface and (anonymous) classes for lower java versions):
public class VehicleUtil {
private static final Map<Class<? extends Vehicle>, Supplier<String>> map = createMap();
private static Map<Class<? extends Vehicle>, Supplier<String>> createMap() {
Map<Class<? extends Vehicle>, Supplier<String>> result = new HashMap<>();
result.put(Vehicle.class, Vehicle::getName);
result.put(Car.class, Car::getName);
result.put(Train.class, Train::getName);
return result;
}
public static String getName(Vehicle vehicle) {
return map.get(vehicle.getClass()).get();
}
public static void main(String[] args) {
System.out.println(VehicleUtil.getName(new Vehicle()));
System.out.println(VehicleUtil.getName(new Car()));
System.out.println(VehicleUtil.getName(new Train()));
}
}
The above is just a more elegant way of doing something like:
public static String getName(Vehicle vehicle) {
return Vehicle.class.equals(vehicle.getClass()) ? Vehicle.getName()
: Car.class.equals(vehicle.getClass()) ? Car.getName()
: Train.class.equals(vehicle.getClass()) ? Train.getName()
: null;
}

What to do with static method overrides?

For example,
public class A {
public static int f() { return 1; }
}
public class B extends A {
public static long f() { return 100L; }
}
Unfortunately B.f() couldn't be compiled because B.f() tries to override A.f(), and so the name clashes because the return types aren't compatible.
I'm weired what's purpose to override a static method? Any use case? Can I just hide away A.f() in class B?
Actual usage:
class EntityDTO {
public static List<EntityDTO> marshal(Collection<? extends Entity> entities) {
...
}
}
class BookDTO extends EntityDTO {
public static List<BookDTO> marshal(Collection<? extends Book> books) {
...
}
}
Strictly speaking, static methods can not be overridden. Method overriding is exclusively a feature of object polymorphism, and static methods doesn't belong to any object but the class itself.
Having clarified that, you should not make any of your methods static. That would solve your problem in hand, at least. As the method arguments are different, it will not be considered as overriding, but overloading.
static methods are not overriden...But it is called method hiding. The benefits of using the same method name and parameters are just like any other method overriding benefits
static method can not be overridden.
Notice: your B.f() should return int rather than long to pass compile.
I can't think of a use case where overriding static functions (in Java) can be useful, but if you ever absolutely must achieve it, here's how:
import java.lang.reflect.Method;
class A {
public static void callOut() {
System.out.println("A.callOut");
}
}
public class B extends A {
public static void callOut() {
System.out.println("B.callOut");
}
public static void main(String[] args) throws Exception
{
A a = new A();
A b = new B();
Method aM = a.getClass().getMethod("callOut");
Method bM = b.getClass().getMethod("callOut");
aM.invoke(null); // prints A.callOut
bM.invoke(null); // prints B.callOut
}
}
Maybe you need to rethink you design, if you have a need to override the marshal method, then it shouldn't be static in the first place.

extends of the class with private constructor

Suppose we have the following code:
class Test {
private Test() {
System.out.println("test");
}
}
public class One extends Test {
One() {
System.out.println("One");
}
public static void main(String args[]) {
new One();
}
}
When we create an object One, that was originally called the parent class constructor Test(). but as Test() was private - we get an error.
How much is a good example and a way out of this situation?
There is no way out. You have to create an available (protected, public or default) super constructor to be able to extend test.
This kind of notation is usually used in utility classes or singletons, where you don't want the user to create himself an instance of your class, either by extending it and instanciating the subclass, or by simply calling a constructor of your class.
When you have a class with only private constructors, you can also change the class to final because it can't be extended at all.
Another solution would be having a method in test which create instances of test and delegate every method call from One to a test instance. This way you don't have to extend test.
class Test {
private Test() {
System.out.println("test");
}
public static Test getInstance(){
return new Test();
}
public void methodA(){
//Some kind of implementation
}
}
public class One {
private final Test test;
One() {
System.out.println("One");
test = Test.getInstance();
}
public void methodA(){
test.methodA();
}
public static void main(String args[]) {
new One();
}
}
Make the constructor of test non-private or move One into test.
BTW, your sample code contains a few issues:
classes should be named title case (Test instead of test)
I'd suggest to make the One's constructor private unless it is called from a different class in the same package
Actually, I found there is a way out. Like this:
class Base {
private Base() {
}
public void fn() {
System.out.println("Base");
}
public static class Child extends Base {
public void fn() {
System.out.println("Child");
}
}
public static Base getChild() {
return new Child();
}
}
Now, you can use getChild() to get instance of the extended class.

java subclass have method to return its class

Ok, maybe this is a stupid question. But i'm just wondering if this can be done in java.
abstract public class ParentClass<T> {
abstract public T getTest();
}
in the subclass
public class SubClass extends ParentClass<MyObject> {
public MyObject getTest() {
// I can return the object with class MyObject
return null;
}
}
My question is can I return the class type in the child method? I mean, is it can be done by adding some code in the ParentClass, so I can do this below?
For example
public class Sub1Class extends parentClass<Object1> {
public Object1 getTest() { }
// I want to have a method that return it's class in the superclass
public Sub1Class getItClassObject() { }
}
other example
public class Sub2Class extends parentClass<Object2> {
public Object2 getTest() { }
// I want to have a method that return it's class in the superclass
public Sub2Class getItClassObject() { }
}
one example again
public class Sub3Class extends parentClass<Object3> {
public Object3 getTest() { }
// I want to have a method that return it's class in the superclass
public Sub3Class getItClassObject() { }
}
if you see, method getItClassObject in Sub1Class, Sub2Class and Sub3Class will follow it's class. But I don't want to add same method for every subclass, just want to add some code (if feasible) in the ParentClasss, so in the subclass, I just can call getItClassObject directly without write all the code in every subclass.
Usually I add method in ParentClass like this.
abstract public class ParentClass<T> {
abstract public T getTest();
public Object getItClassObject() { }
}
so in the subclass I just instance the class, but I have to cast again :(
Sub1Class sub1Class = new Sub1Class();
Sub1Class after1Cast = (Sub1Class) sub1Class.getItClassObject();
Sub2Class sub2Class = new Sub2Class();
Sub2Class after2Cast = (Sub2Class) sub2Class.getItClassObject();
I think it cannot be done in java. But I don't know if there is a clue to solve this. Thanks
This is what you want I think. The following compiles:
abstract class A {
public abstract A getA();
}
class B extends A {
// Declared to return a B, but it still properly overrides A's method
#Override
public B getA() {
return new B();
}
}
class C extends A {
// Declared to return a B, but it still properly overrides A's method
#Override
public C getA() {
return new C();
}
}
As you can see, A declares that the getA() method returns an A. But, you can restrict the return type in subclasses as shown.
I'm not sure if I understand your intent correctly, but I think the built-in Object.getClass() method will do what you want. Given classes defined as:
public abstract class ParentClass<T> {
public abstract T getTest();
}
class SubClassString extends ParentClass<String> {
public String getTest() {
return "";
}
}
class SubClassInteger extends ParentClass<Integer> {
public Integer getTest() {
return Integer.valueOf(0);
}
}
getClass() will return the correct run-time class
public static void main(String[] args) {
SubClassString subString = new SubClassString();
// displays "class SubClassString"
System.out.println(subString.getClass());
SubClassInteger subInteger = new SubClassInteger();
// displays "class SubClassInteger"
System.out.println(subInteger.getClass());
ParentClass<?> parentInstance = new SubClassInteger();
// displays "class SubClassInteger"
System.out.println(parentInstance.getClass());
}
The only way I can think of is by telling the parent class what the subclass is when you extend it (just like you did with 'T'). Eg:
public abstract class ParentClass<T,U> {
abstract public T getTest();
abstract public U getItClassObject();
}
They you define your subclass like so:
public class Sub1Class extends ParentClass<Object1,Sub1Class> {
public Object1 getTest() { }
public Sub1Class getItClassObject() { }
}
Then you can do what you want without the typecast:
Sub1Class sub1Class = new Sub1Class();
Sub1Class after1Cast = sub1Class.getItClassObject();
If your objects have no-arg constructors (or some consistent form of constructor across all of them), you can use reflection to do it. Some pseudocode would be
public class MyClass {
public MyClass instantiateType() {
Class<?> actualClass = getClass();
return actualClass.newInstance();
}
}
This is using the runtime type of the class, so subclasses will return their type. This works only for a no-arg constructor though.

Categories

Resources