I did Java to make (a == 1 && a == 2 && a == 3) always true

The original story is this article on StackOverflow JavaScript. https://stackoverflow.com/questions/48270127/can-a-1-a-2-a-3-ever-evaluate-to-true

As a seed reveal, ** If you override the implicit type conversion in JavaScript and put the processing there, you can execute it at the time of comparison! ** ** That's why you can go with Java if you override it with the inherited class!

Java implicit type conversion

Just in case, let's check Java's implicit type conversion.

    @Test
    public void test_integer() {
        Integer a = Integer.valueOf(1);

        if(a == 1){
            System.out.println("true");
        }
    }

This is compared by calling ʻintValue () of ʻInteger when comparing with int. In Java, it's called unboxing.

Inherit Integer and override intValue

Failed because the Integer class is final and cannot be overridden Or rather, if you override the intValue of Integer, you will die in various ways.

Inherit Number and override intValue

So, let's create a numeric class by inheriting the Number class, which is the abstract class of the parent of Integer.


public class StrangeObject extends Number implements Comparable<Integer>{

    private int value;

    public StrangeObject(int value){
        this.value = value;
    }

    @Override
    public int intValue() {
        value++;
        return value;
    }

    @Override
    public long longValue() {
        value++;
        return value;
    }

    @Override
    public float floatValue() {
        value++;
        return value;
    }

    @Override
    public double doubleValue() {
        value++;
        return value;
    }

    public int compareTo(Integer outerValue) {

        return (value < outerValue) ? -1 : ((value == outerValue) ? 0 : 1);
    }
}

Since I implemented intValue () and also implemented the interface of Comparable It seems to be comparable to int!

    @Test
    public void test_a1a2a3() throws Exception {

        StrangeObject a = new StrangeObject(0);

        if(a == 1 && a == 2 && a == 3){
            System.out.println("true");
        }
    }
Error:(22, 14) java:Types StrangeObject and int cannot be compared

It's useless to check the type before comparison ...

    @Test
    public void test_a1a2a3() throws Exception {

        StrangeObject a = new StrangeObject(0);

        if(a.intValue() == 1 && a.intValue() == 2 && a.intValue() == 3){
            System.out.println("true");
        }
    }

This works, but what should I do to remove (implicitly execute) intValue ()?

Rewrite Integer

From here onward, the darkness will be quite deep, so let's just check it.

Since it was pointed out in the comment that it will not be unboxed unless it is in some system classes Rewrite the system class.

Use Javassist to rewrite the Integer class file.

In the case of system class, it cannot be rewritten at runtime, so It is spit out as a static file once, and the rewritten file is read at runtime.

    @Test
    public void testIntegerExport() throws Exception {

        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get("java.lang.Integer");
        CtMethod method = cc.getDeclaredMethod("intValue");

        //value in intValue++Added
        method.insertBefore("value++;");

        //Output the modified class file
        cc.writeFile();

    }

Executing this test method will output the rewritten Integer class to ./java/lang/Integer.class.

Then create the following main class.

public class A123 {
    public static void main(String[] args){
        
        Integer a = Integer.valueOf(0);

        if(a == 1 && a == 2 && a == 3){
            System.out.println(true);       
        }
    }
}

For run-time arguments Add -Xbootclasspath / p: ..

This will load the modified Integer class.

However, if you load this class

java.lang.InternalError 
 - klass: 'java/lang/InternalError'
#
# A fatal error has been detected by the Java Runtime Environment:
#
...

It cannot be executed probably because the value of Integer fluctuates when the JVM is executed.

So I will modify the Integer file further.

Rewrite Integer (revised)

Make it an Integer class that works normally from the start of VM execution until the main class is executed.

    @Test
    public void testIntegerExport2() throws Exception {

        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get("java.lang.Integer");
        CtMethod m = cc.getDeclaredMethod("intValue");

        //Have a flag inside
        CtField isBroken = new CtField(CtClass.booleanType, "isBroken", cc);
        isBroken.setModifiers(Modifier.PUBLIC);
        cc.addField(isBroken, CtField.Initializer.constant(false));

        //Add only if the flag is enabled
        m.insertBefore("if(isBroken) value++;");

        //Output the modified class file
        cc.writeFile();

    }

Add flag change processing to the main class.

public class A123 {
    public static void main(String[] args) {

        Integer a = Integer.valueOf(0);

        try {
            //Rewrite isBroken with reflection to avoid compilation errors
            Integer.class.getField("isBroken").setBoolean(a, true);

            if (a == 1 && a == 2 && a == 3) {
                System.out.println(true);
            }

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

    }
}

If you try to change the value for an Integer isBroken If you rewrite it normally, the field does not exist, so I get a compile error. Therefore, by rewriting with reflection, a run-time error will occur if it does not exist. You can see the horror of reflection ...

Execution result Also, if you add -Xbootclasspath / p: . to the run-time argument and execute it,

true

I was able to successfully change (a == 1 && a == 2 && a == 3) to true in Java.

Summary

Recommended Posts

I did Java to make (a == 1 && a == 2 && a == 3) always true
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
I tried to make a login function in Java
How to make a Java container
How to make a Java array
I want to make a list with kotlin and java!
I just wanted to make a Reactive Property in Java
I want to make a function with kotlin and java!
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
I tried to make a client of RESAS-API in Java
How to make a Discord bot (Java)
[Java] I tried to make a maze by the digging method ♪
I tried to make Basic authentication with Java
java I tried to break a simple block
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
What I did when I converted java to Kotlin
I tried to make a talk application in Java using AI "A3RT"
I tried to break a block with java (1)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Javassist second decoction)
[Small story] I tried to make the java ArrayList a little more convenient
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (black magic edition)
I tried to create a Clova skill in Java
I used to make nc (netcat) with JAVA normally
[Java] Make it a constant
Make a rhombus using Java
I tried to create a java8 development environment with Chocolatey
I tried to modernize a Java EE application with OpenShift.
[Java] I want to convert a byte array to a hexadecimal number
[Beginner] Try to make a simple RPG game with Java ①
[Beginner] I made a program to sell cakes in Java
I want to make a specific model of ActiveRecord ReadOnly
I tried using Hotwire to make Rails 6.1 scaffold a SPA
I tried to make Java Optional and guard clause coexist
I tried to convert a string to a LocalDate type in Java
I made a Dockerfile to start Glassfish 5 using Oracle Java
[Java] I tried to make a rock-paper-scissors game that beginners can run on the console.
Try to make a simple callback
I created a PDF in Java.
I made a shopify app @java
How to make a JDBC driver
I tried to interact with Java
[Java] How to create a folder
How to make a splash screen
How to make a Jenkins plugin
How to make a Maven project
I tried to summarize Java learning (1)
I tried to summarize Java 8 now
Try to make a peepable iterator
[Unity] I tried to make a native plug-in UniNWPathMonitor using NWPathMonitor
I made a method to ask for Premium Friday (Java 8 version)
I tried to make an Android application with MVC now (Java)
How to make a groundbreaking diamond using Java for statement wwww
I tried to make a group function (bulletin board) with Rails
I tried to make a simple face recognition Android application using OpenCV
I want to write a nice build.gradle
I want to make an ios.android app
I tried to summarize Java lambda expressions
I was addicted to a simple test of Jedis (Java-> Redis library)
[Java / kotlin] Kai-How to make a Discord Bot-Let's implement a command to say hello-
[iOS] I tried to make a processing application like Instagram with Swift
[JAVA] Project Euler, I got stuck in Q8, so make a note