0

I have a situation where I check for the instanceOf some classes for proceeding with my logic.

For eg.

if (obj instanceof X) { result = true; } 

But now this is being used in lot of places in my legacy code.

My problem is now this instanceOf should return true only if some global property variable is true.

I am looking for an alternative solution to replacing all these instanceOf checks as shown below:

if (GLOBALPROPERTY == true) { if (obj instanceof X) { result = true; } } 

Can I inject this check inside the class X itself so that, it will return false wherever I check for instanceOf this class.

7
  • Do all of the classes you use this on have a common ancestor class? Commented Oct 27, 2013 at 11:05
  • 4
    Also, you could just do result = obj instanceof X instead of the if. Commented Oct 27, 2013 at 11:07
  • @R.J: Not if result may already be true and he doesn't want it reset to false. Commented Oct 27, 2013 at 11:09
  • So To be precise, only when the global property is true, I will have these classes loaded, otherwise these classes will be not found. So If I simply call result = obj instanceof X, it should throw a NoClassDefFoundError exception. Commented Oct 27, 2013 at 11:11
  • @T.J.Crowder - If it was already true, what would be the exact use of that if and result = true;?! Nevertheless, it was just a suggestion which could help the OP remove some (possible) extra code. Nothing else. Commented Oct 27, 2013 at 11:13

1 Answer 1

1

No, you can't.

The nearest thing I can think of is aspect-oriented programming with AspectJ. But that would be tricky - you'd probably have to switch from using instanceof to using proper polymorphic method calls, first.

But pragmatically, you'll probably just have to do a search and replace through your entire codebase.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.