Python 官方文档:入门教程 => 点击学习
目录前言jOOR特点常用api测试测试APIS代理功能jOOR实现方式动态编译结论前言 Java中的原生反射库虽然方法不多,但写起来却非常繁琐, 比如: public static
Java中的原生反射库虽然方法不多,但写起来却非常繁琐, 比如:
public static <T> T create(HttpRequest httpRequest) {
Object httpRequestEntity = null;
try {
Class<T> httpRequestEntityCls = (Class<T>) Class.forName(HttpProcessor.PACKAGE_NAME + "." + HttpProcessor.CLASS_NAME);
Constructor con = httpRequestEntityCls.getConstructor(HttpRequest.class);
httpRequestEntity = con.newInstance(httpRequest);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return (T) httpRequestEntity;
}
就实现一个对象的构造都需要写一长串代码,特别是异常处理非常污染视觉。
发现有一个第三方库:jOOR,通过链式DSL接口,简化了反射过程,
比如:
@Test
void should_get_World() {
String result = Reflect.onClass("java.lang.String") // 类似Class.forName()
.create("Hello World") // 调用构造器
.call("substring", 6) // 调用方法
.call("toString") // 调用方法
.get(); // 获取最终包装类
assertThat(result).isEqualTo("World");
}
再比如:原有java代码写法:
try {
Method m1 = department.getClass().getMethod("getEmployees");
Employee employees = (Employee[]) m1.invoke(department);
for (Employee employee : employees) {
Method m2 = employee.getClass().getMethod("getAddress");
Address address = (Address) m2.invoke(employee);
Method m3 = address.getClass().getMethod("getStreet");
Street street = (Street) m3.invoke(address);
System.out.println(street);
}
}
// There are many checked exceptions that you are likely to ignore anyway
catch (Exception ignore) {
// ... or maybe just wrap in your preferred runtime exception:
throw new RuntimeException(e);
}
采用jOOR后的写法:
Employee[] employees = on(department).call("getEmployees").get();
for (Employee employee : employees) {
Street street = on(employee).call("getAddress").call("getStreet").get();
System.out.println(street);
}
已经非常的简洁了。
测试类:
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name) {
this.name = name;
}
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;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
@Test
void test_joor_apis() {
// 【创建类】
Person person = Reflect.onClass(Person.class).create("steven").get();// 有参构造器
//Person person = Reflect.onClass(Person.class).create().get(); // 无参构造器
assertThat(person.toString()).isEqualTo("Person{name='steven', age=0}");
// 【调用方法】
Reflect.on(person).call("setName", "steven2");
String name = Reflect.on(person).call("getName").toString();
assertThat(name).isEqualTo("steven2");
// 【设置变量的值】
int age = Reflect.on(person).set("age", 18).get("age");
assertThat(age).isEqualTo(18);
// 【得到变量】
name = Reflect.on(person).field("name").get();// 方式一
assertThat(name).isEqualTo("steven2");
name = Reflect.on(person).get("name");// 方式二
assertThat(name).isEqualTo("steven2");
}
jOOR代理是实现的静态代理功能,首先创建静态代理相关类
interface HelloWorld {
void print();
}
class HelloWorldImpl implements HelloWorld {
public void print() {
System.out.println("Hello World");
}
}
class StaticProxy implements HelloWorld {
private HelloWorld helloWorld;
public StaticProxy(HelloWorld helloWorld) {
this.helloWorld = helloWorld;
}
public void print() {
System.out.println("Before Hello World!");
helloWorld.print();
System.out.println("After Hello World!");
}
}
使用方法区别:
传统方式:
@Test
void test_proxy_nORMal() {
StaticProxy staticProxy = new StaticProxy(new HelloWorldImpl());
staticProxy.print();
}
@Test
void test_proxy_jOOR() {
Reflect.onClass(StaticProxy.class)//反射调用StaticProxy
.create(new HelloWorldImpl())//调用构造器
.as(HelloWorld.class)//作为HelloWorld接口的代理
.print();
}
此时要求代理类和业务类具有相同的方法,才能通过调用代理的方法,负责抛出ReflectException
异常
org.joor.ReflectException: java.lang.NoSuchMethodException: No similar method print with params [] could be found on type class StaticProxy.
at org.joor.Reflect.call(Reflect.java:585)
at org.joor.Reflect$1.invoke(Reflect.java:756)
特殊情况
当业务类为map类型,此时会把POJO的getter和setter转换成map的put和get
// [#14] Emulate POJO behaviour on wrapped map objects
catch (ReflectException e) {
if (isMap) {
Map<String, Object> map = (Map<String, Object>) object;
int length = (args == null ? 0 : args.length);
if (length == 0 && name.startsWith("get")) {
return map.get(property(name.substring(3)));
}
else if (length == 0 && name.startsWith("is")) {
return map.get(property(name.substring(2)));
}
else if (length == 1 && name.startsWith("set")) {
map.put(property(name.substring(3)), args[0]);
return null;
}
}
jOOR提供了可选的依赖java.compiler
可以简化 javax.tools.JavaCompiler
编译代码,
如下所示:
@Test
void test_compile_on_runtime() {
Supplier<String> supplier = Reflect.compile(
"com.example.HelloWorld",
"package com.example;\n" +
"class HelloWorld implements java.util.function.Supplier<String> {\n" +
" public String get() {\n" +
" return \"Hello World!\";\n" +
" }\n" +
"}\n").create().get();
String result = supplier.get();
assertThat(result).isEqualTo("Hello World!");
}
通过以上案例可以看出,jOOR由于其链式编程的特性,对代码的简化和可扩展性要强Java自带反射库和其他第三方库(apache、hutool等),且其包含了一些高级应用,如代理等。
到此这篇关于Java效率提升神器jOOR的文章就介绍到这了,更多相关Java jOOR内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java效率提升神器jOOR
本文链接: https://lsjlt.com/news/153750.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0