Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (gray magic that is not so much as black magic)

I was inspired by the article below.

I want to output true in Java with a == 1 && a == 2 && a == 3 --Qiita I want to output true in Java with a == 1 && a == 2 && a == 3 (PowerMockito edition) --Qiita I want to output true in Java with a == 1 && a == 2 && a == 3 (black magic edition) --Qiita I want to output true in Java with a == 1 && a == 2 && a == 3 (black edition) --Qiita

Since it was realized by Proxy of Java standard library, it is necessary to implement the interface.

Entry point


public static void main(String... args) throws Exception {
	{
		System.out.println("First of all, if you execute it normally ...");
		Judge judge = new JudgeImpl();
		test(judge);
	}
	{
		System.out.println("If you bite the Proxy ...");
		Judge judge = new AlwaysTrue.Builder()
				.addInterface(Judge.class)
				.build(JudgeImpl.class);
		test(judge);
	}
}

private static void test(Judge judge){
	System.out.println( judge.judge(1) );
	System.out.println( judge.judge(2) );
	System.out.println( judge.judge(3) );
}

Judgment logic


public class JudgeImpl implements Judge{
    public boolean judge(int a) {
        if (a == 1 && a == 2 && a == 3) {
            return true;
        } else {
            return false;
        }
    }
}

Interface for which the processing result is rewritten


public interface Judge {
    public boolean judge(int a);
}

Proxy class that rewrites the processing result


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**In the interface specified by the addInterface method
The return value is(B|b)If there is a boolean method, the result will be true*/
public class AlwaysTrue{

	public static class Builder{
		List<Class<?>> interfaces = new ArrayList<>();
		public Builder addInterface(Class<?> interfaze) {
			interfaces.add(interfaze);
			return this;
		}
		private Class<?>[] getInterfacesArray(){
			Class<?>[] clazzArr = new Class[interfaces.size()];
			for( int i =0;i<interfaces.size();i++) {
				clazzArr[i] = interfaces.get(i);
			}
			return clazzArr;
		}

		public <E> E build(Class<?> clazz) throws Exception {
			Object normalInstance = clazz.newInstance();
			Object prankInstance = Proxy.newProxyInstance(
					clazz.getClassLoader(),
					getInterfacesArray(),
					new AlwaysTrueHandler(normalInstance));
			@SuppressWarnings("unchecked")
			E o = (E)prankInstance;
			return o;
		}
	}

	private static class AlwaysTrueHandler implements InvocationHandler {
		private Object normalInstance;
		public AlwaysTrueHandler( Object normalInstance){
			this.normalInstance = normalInstance;
		}
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			Object normalValue =  method.invoke(normalInstance, args);
			if( method.getReturnType() == Boolean.class
					|| method.getReturnType() == boolean.class ){
				System.out.println("Really`"+normalValue+"`I heard you want to return`true`I'll return!");
				return true;
			}
			return normalValue;
		}
	}
}

Execution result

First of all, if you execute it normally ...
false
false
false
If you bite the Proxy ...
Really`false`I heard you want to return`true`I'll return!
true
Really`false`I heard you want to return`true`I'll return!
true
Really`false`I heard you want to return`true`I'll return!
true

Recommended Posts

Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (gray magic that is not so much as black magic)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (black magic edition)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Royal road edition that is neither magic nor anything)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (Javassist second decoction)
I want to ForEach an array with a Lambda expression in Java
I wanted to make (a == 1 && a == 2 && a == 3) true in Java
Output true with if (a == 1 && a == 2 && a == 3) in Java (Invisible Identifier)
Even if I want to convert the contents of a data object to JSON in Java, there is a circular reference ...
I want to make a list with kotlin and java!
I want to make a function with kotlin and java!
I want to create a Parquet file even in Ruby
[Java] I want to test standard input & standard output with JUnit
I want to write a loop that references an index with Java 8's Stream API
I want to Flash Attribute in Spring even if I set a reverse proxy! (do not do)
A collection of patterns that you want to be aware of so as not to complicate the code
A story that I struggled to challenge a competition professional with Java
[Java] I want to perform distinct with the key in the object
[Java] JUnit that NG if a method with a large number of lines is detected using black magic
I want to select multiple items with a custom layout in Dialog
I want to create a dark web SNS with Jakarta EE 8 with Java 11
I want to display a PDF in Chinese (Korean) with thin reports
A story that suffered from a space that does not disappear even if trimmed with Java The cause is BOM
I tried to make a program that searches for the target class from the process that is overloaded with Java
Let's create a TODO application in Java 2 I want to create a template with Spring Initializr and make a Hello world
I want to send an email in Java.
I did Java to make (a == 1 && a == 2 && a == 3) always true
I want to use java8 forEach with index
rsync4j --I want to touch rsync in Java.
I tried to output multiplication table in Java
I want to be eventually even in kotlin
[Java] Something is displayed as "-0.0" in the output
I tried to break a block with java (1)
I want to solve the problem that JS is not displayed properly unless reloaded when transitioning with Turbolinks: link_to
I want to find the MD5 checksum of a file in Java and get the result as a string in hexadecimal notation.
I used Docker for my portfolio as a beginner, so I hope that even 1mm will be helpful to someone.
MockMVC returns 200 even if I make a request to a path that does not exist
I want to use PowerMock in a class that combines parameterized tests and ordinary tests
7 things I want you to keep so that it doesn't become a fucking code
I want to return an object in CSV format with multi-line header & filter in Java
[Java] The problem that true was returned as a result of comparing Integer with ==
If hash [: a] [: b] [: c] = 0 in Ruby, I want you to extend it recursively even if the key does not exist.
[Java] Dealing with the situation where the program that writes to the Output Stream of Process does not end even if waitFor
I want to use Combine in UIKit as well.
I want to do something like "cls" in Java
I want to use ES2015 in Java too! → (´ ・ ω ・ `)
I want to use a little icon in Rails
I tried to create a Clova skill in Java
I want to monitor a specific file with WatchService
I tried to make a login function in Java
I dealt with Azure Functions not working in Java
I want to define a function in Rails Console
I want to transition screens with kotlin and java!
I want to click a GoogleMap pin in RSpec
Java11: Run Java code in a single file as is
I want to get along with Map [Java beginner]
How to batch initialize arrays in Java that I didn't know when I was a beginner
[CQ Engine] I want to handle collections like Stream or .Net LINQ even in Java 7.
I want to return a type different from the input element with Java8 StreamAPI reduce ()
A story that I realized that I had to study as an engineer in the first place