ReflectASM的使用

1.测试类
public class Test {

	public static void main(String[] args) {
		
		//------------------------------------------------------
		Person p = new Person();
		MethodAccess access = MethodAccess.get(Person.class);
		int setNameIndex = access.getIndex("setName");
		access.invoke(p, setNameIndex, "Awesome McLovin");
		int getNameIndex = access.getIndex("getName");
		String name = (String) access.invoke(p, getNameIndex);
		System.out.println(name);
		
		//------------------------------------------------------
		Person p1 = new Person();
		FieldAccess access1 = FieldAccess.get(Person.class);
		int nameIndex = access1.getIndex("name");
		access1.set(p1, nameIndex, "Awesome McLovin");
		String name1 = (String) access1.get(p1, nameIndex);
		System.out.println(name1);
		
		//------------------------------------------------------
		ConstructorAccess<Person> access2 = ConstructorAccess.get(Person.class);
		Person p2 = access2.newInstance();
		System.out.println(p2);
	}
}


2.Person类


package com.hxrainbow.reflect;

public class Person {

	private int id;
	public String name;
	private int age;
	private String address;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	
	
}

3.当有方法重载时,会有问题,可以这样来解决:

在Person类中加入方法重载:

public String getName(String name1) {
	System.out.println("===========");
	return name;
}

调用此方法:

int getNameIndex = access.getIndex("getName",String.class);
String name = (String) access.invoke(p, getNameIndex,"11");
System.out.println(name);


你可能感兴趣的:(reflectASM)