Deep Joshi
Deep Joshi

Reputation: 502

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()

Upvotes: 2

Views: 681

Answers (2)

Joni
Joni

Reputation: 111229

There is no way the A.amthu() method can detect it was called using a variable of the type B.

Static methods in Java have fundamental limitations such as this. These limitations are why you don't see static methods used very much in Java. In particular, calling static methods using object instances like b.amthu() is discouraged because it leads to confusion - see also Why isn't calling a static method by way of an instance an error for the Java compiler?

You can get around this by passing the class you expect as a variable to A.amthu:

// call method
A.amthu(B.class);

// method declaration in A
static void amthu(Class<? extends A> klass) { ... }

Or perhaps you can rework your code to avoid using static fields and methods altogether. It's impossible to tell you what that would look like without knowing what you're trying to do here though.

Upvotes: 1

s_mstdib
s_mstdib

Reputation: 1

You can do instanceof check and then print B.x or A.x

If(this instanceof A) System.out.println A.x else System.out.println B.x

Upvotes: 0

Related Questions