コードを叩くエージェント調査

2860 ワード

package test;

import java.lang.reflect.*;
import java.util.Arrays;
import java.util.Random;

public class ProxyTest {

	public static void main(String[] args) {
		Object[] elements = new Object[100];
		for (int i = 0; i < elements.length; i++) {
			Integer value = i + 1;
			InvocationHandler handler = new TraceHandler(value);
			Object proxy = Proxy.newProxyInstance(null,
					new Class[] { Comparable.class }, handler);
			elements[i] = proxy;

		}
		Integer key = new Random().nextInt(elements.length + 1) + 1;
		int result = Arrays.binarySearch(elements, key);
		if (result >= 0) {
			System.out.print(elements[result]);
		}
	}

}
class TraceHandler implements InvocationHandler{

	private Object target;
	
	public TraceHandler(Object t){
		this.target = t;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.print(target);
		System.out.print("." + method.getName() + "(");
		if (args != null) {
			for (int j = 0; j < args.length; j++) {
				System.out.print(args[j]);
				if (j < args.length - 1) {
					System.out.print(", ");
				}
			}
		}
		System.out.println(")");
		return method.invoke(target, args);
	}
	
}

Integerパッケージクラス完全形式:public final class Integer extends Number implements Comparable{...}Comparableインタフェースを実現しました.method.invoke(target,args)は具体的な実装クラスを見つけた.
自己エンコード:
package test;

import java.lang.reflect.*;

public class ProxyAPITest {

	public static void main(String[] args) {
		
		final ProxyAPI proxyA = new ProxyAPIImpl();
		
		Object elements = new Object();
		InvocationHandler handler = new TraceAPIHandler(elements);
		Object proxy = Proxy.newProxyInstance(null,
				new Class[] { ProxyAPI.class }, handler);
		
		ProxyAPI proxyAPI = (ProxyAPI)elements;
		proxyAPI.hello();
	}

}

class TraceAPIHandler implements InvocationHandler{

	private Object target;
	
	public TraceAPIHandler(Object t){
		this.target = t;
	}
	
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.print(target);
		System.out.print("." + method.getName() + "(");
		if (args != null) {
			for (int j = 0; j < args.length; j++) {
				System.out.print(args[j]);
				if (j < args.length - 1) {
					System.out.print(", ");
				}
			}
		}
		System.out.println(")");
		return method.invoke(target, args);
	}
	
}
package test;

public interface ProxyAPI {
	
	public void hello();
	
}
package test;

public class ProxyAPIImpl implements ProxyAPI {
	
	public void hello(){
		System.out.println("  ,     ,         !");
	}
	
}
結果:エラーが発生し、「interface test.ProxyAPI is not visible from class loader」と報告されたが、まだ分からない.エージェントはエージェントという概念に相当し、少し信じられず、調査を続ける必要があると紹介された.