I played with this, and so far I have not been able to find a way to hide or trick instanceof into returning false by hiding its type through obfuscation layers, but this does not mean this is impossible, since I am far from the most knowledgeable person about Java. So I came to ask the experts.
I tried the following combinations, and in each case the instanceof operator can identify the true / base type of the object.
public class Test { public static void main(String[] args) { Object o = new TestObject(); printType("Base Class", o); o = (TestSuperObject)(new TestObject()); printType("Super Class", o); o = (TestInterface)(new TestObject()); printType("Interface", o); o = (TestInterface)((TestSuperObject3)(new TestObject3())); printType("Interface on Super Class", o); o = (TestSuperObject3)((TestInterface)(new TestObject3())); printType("Super Class on Interface", o); } private static void printType(String testCase, Object o) { System.out.println(testCase); System.out.println("TestObject:" + (o instanceof TestObject)); System.out.println("TestObject2:" + (o instanceof TestObject2)); System.out.println("TestObject3:" + (o instanceof TestObject3)); System.out.println(); } }
Classes are defined as ...
public class TestObject extends TestSuperObject implements TestInterface public class TestObject2 extends TestSuperObject implements TestInterface public interface TestInterface public class TestSuperObject public class TestObject3 extends TestSuperObject3 public class TestSuperObject3 implements TestInterface
So, basically, is there a way to hide this information or somehow lose type information? I do not ask, because I have a reason to do this, but I would like to know and be careful in the future, if possible. Besides, I'm just curious.
source share