0

Say

class E extends B {}
class B extends A {}

We have,

B v = new E();
process(v);

We know it is true that,

v.getClass() == E.class

Is there a way to tell the static binding for v is exactly B programmatically?

EDIT: The original idea was to have a one line check for overloaded methods. Something like,

   process(A a) {
     // ... code for a.processABC();
     if (a.getStaticBindingClass() == B.class) { // not a subclass of B
        // Additional logic for statical binding case.
         ... 
     }
     // ... code for a.processDEF();
   }

It is possible to introduce process(B b); However, there is lots of copy code from process(A a).

CrepuscularV
  • 983
  • 3
  • 12
  • 25
  • It depends on how you are using `v`. Is it a field? – Daniel Pryden Dec 14 '17 at 10:45
  • v is a local variable in some methods. Why does it matter whether v is a field or not? – CrepuscularV Dec 14 '17 at 10:51
  • could you give more info on the context? what you want to do? – martidis Dec 14 '17 at 10:53
  • If it's a local variable, it may not even *exist* by the time the code is JITted: the JIT could inline, stack-allocate, enregister, etc. You need to show the code that's using `v` and wants to know its static type. – Daniel Pryden Dec 14 '17 at 10:56
  • `B.class.isAssignable(v.getClass())`? – Lino Dec 14 '17 at 12:02
  • 1
    The question is: why would you do that? It might be an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). – MC Emperor Dec 14 '17 at 12:13
  • Possible duplicate of [Check if a object is a instance of a class (but not a instance of its subclass)](https://stackoverflow.com/questions/16688655/check-if-a-object-is-a-instance-of-a-class-but-not-a-instance-of-its-subclass) – tkruse Dec 15 '17 at 03:22
  • Edited the original question. The difference if the Possible duplicate one is here I need an exact match case and a subclass. – CrepuscularV Dec 17 '17 at 06:53
  • You need to look up the Visitor pattern. – user207421 Dec 17 '17 at 07:13

0 Answers0