dimanche 16 août 2020

static method can't access caller class name

I have 2 classes A and B where B extends A. Both class are having a static variable x. There is one static method defined in class A which is accessing x. When I call the method with B from main, is there any way to know the caller of the function? With that caller class name I can use reflection in order to get value of x from class B.

public class Test {
    public static void main(String[] args) throws Exception {
        A a = new A();
        B b = new B();
        b.amthu();
    }
    private static class A {
        public static String x = "static string from A";
        public static void amthu() throws NoSuchFieldException, IllegalAccessException {
            System.out.println(/* what can be the line here?*/);
        }
    }
    private static class B extends A {
        public static String x = "static string from B";
    }
}

I have similar code in python which works fine because of the class method having cls as arguments but static method doesn't have such thing and in Java I am only aware of static methods so can't access value of x from sub-class B.

class A:
    x = "static value of A"

    @classmethod
    def amthu(cls):
        print(getattr(cls, "x", None))


class B(A):
    x = "static value of B"


a = A()
b = B()
b.amthu()




Aucun commentaire:

Enregistrer un commentaire