Question

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.

Était-ce utile?

La solution

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top