当前位置: 首页 > 工具软件 > ReflectASM > 使用案例 >

java 反射 asm,Java反射工具包reflectasm

赖明煦
2023-12-01

1、

com.esotericsoftware

reflectasm

1.11.9

1、实体类

package com.redisson;

/**

* @Description TODO

* @Date 2020/7/28 13:41

* @Author zsj

*/

public class Person {

public int age;

public String name;

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String say(int age, String name) {

return "hh+" + age + "---" + name;

}

}

2、测试类

package com.redisson;

import com.esotericsoftware.reflectasm.ConstructorAccess;

import com.esotericsoftware.reflectasm.FieldAccess;

import com.esotericsoftware.reflectasm.MethodAccess;

/**

* @Description TODO

* @Date 2020/9/10 9:15

* @Author zsj

*/

public class ReflectasmTest {

public static void main(String[] args) {

// testReflectAsm4Name();

// testReflectAsm4Index();

// testFieldAccess();

// testConstructorAccess();

testIndex();

}

/**

* ReflectAsm反射调用方法

* 用名称定位反射方法

*/

public static void testReflectAsm4Name() {

Person target = new Person();

MethodAccess access = MethodAccess.get(Person.class);//生成字节码的方式创建UserServiceMethodAccess

long start = System.currentTimeMillis();

for (int i = 0; i < 100000000; i++) {

Object object = access.invoke(target, "say", i, i + "hhhll");

// System.out.println(object);

}

long end = System.currentTimeMillis();

System.out.println("timeout=" + (end - start));//523 382 415 489 482

}

/**

* ReflectAsm反射调用方法

* 用方法和字段的索引定位反射方法,性能高

*/

public static void testReflectAsm4Index() {

Person target = new Person();

MethodAccess access = MethodAccess.get(Person.class);

int index = access.getIndex("say", int.class, String.class);

long start = System.currentTimeMillis();

for (int i = 0; i < 100000000; i++) {

access.invoke(target, index, 1, "zhangsan");

}

long end = System.currentTimeMillis();

System.out.println("timeout=" + (end - start));//12 15 23 14 24

}

/**

* ReflectAsm反射来set/get字段值

*/

public static void testFieldAccess() {

Person target = new Person();

FieldAccess fieldAccess = FieldAccess.get(target.getClass());

long start = System.currentTimeMillis();

for (int i = 0; i < 100000000; i++) {

fieldAccess.set(target, "age", 100);

}

long end = System.currentTimeMillis();

System.out.println("timeout=" + (end - start));

int state = (Integer) fieldAccess.get(target, "age");

System.out.println(state);

}

/**

* ReflectAsm反射来调用构造方法

*/

public static void testConstructorAccess() {

ConstructorAccessconstructorAccess = ConstructorAccess.get(Person.class);

Person person = constructorAccess.newInstance();

System.out.println(person);

}

/**

* 查找方法的索引

*/

public static void testIndex() {

Person target = new Person();

MethodAccess methodAccess = MethodAccess.get(target.getClass());

int index = methodAccess.getIndex("say", int.class, String.class);

System.out.println(index);

}

}

 类似资料: