7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Java でもa == 1 && a == 2 && a == 3でtrueって出力させたい(黒魔術編)

Posted at

前書き

Java でもa == 1 && a == 2 && a == 3でtrueって出力させたい の黒魔術編です。

動作環境

  • Java8
  • javassist 3.22.0-GA

ロジック等

Javaなので(?)、if判定部分は別のクラスに抜き出します。
引数の値を書き換える訳ではないので、staticなメソッドにします。

package study.javassist;

public class Judge {

	public static boolean judge(int a) {

		if (a == 1 && a == 2 && a == 3) {
			return true;
		} else {
			return false;
		}

	}

}

上記クラスを呼び出す、メインクラスは以下です。

package study.javassist;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class JudgeCall {

	public static void main(String[] args) {
		try {
			new JudgeCall().execute();
		} catch (NotFoundException | CannotCompileException e) {
			e.printStackTrace();
		}
	}

	private void execute() throws NotFoundException, CannotCompileException {
		ClassPool cp = ClassPool.getDefault();
		CtClass cc = cp.get("study.javassist.Judge");
		CtMethod method = cc.getDeclaredMethod("judge");
		
		String newJudgeMethod = "{return true;}";
		method.setBody(newJudgeMethod);
		
		cc.toClass();

		System.out.println(Judge.judge(1));
		System.out.println(Judge.judge(2));
		System.out.println(Judge.judge(3));
		System.out.println(Judge.judge(4));
	
	}
}

結果

true
true
true
true

解説

execute()メソッドの中で、study.javassist.Judgeクラスのjudgeメソッドの処理内容を書き換えて、常にtrueになるようにしています。

やってみた感想

javassist、なんとなく避けてたけどシステムの基盤部分を扱う際に使えるのでは?
次に機会があったら検討してみる。

7
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?