class A {
static A STATIC_A = new A();
A() {}
}
boolean isComingFromStaticField(Object a) {
// returns true if a comes from static field, for example A.STATIC_A
// returns false if a comes from non-static field/variable, for example new A()
// .. or vice versa ...
}
In Java reflection, what will be the way to know the difference between an object from static field and a "normal" field/variable?
There's no such thing as a "static instance" and a "normal instance". There are only static variables (and methods etc). So for example:
public class Foo {
static Object bar = new Object();
Object baz = bar;
}
Here the values of baz
and bar
refer to the same object - despite the fact that one variable is static and one is an instance variable.
Now if you just want to check whether a particular reference is equal to A.STATIC_INSTANCE
, that's a simple reference equality check:
boolean isStaticInstance(Object a) {
return a == A.STATIC_INSTANCE;
}
... but be aware that all that's checking is reference equality. You should avoid using misleading terminology like "static instance" after clarifying in your own mind what you really mean.
See more on this question at Stackoverflow