java 实现反射 json动态转实体类--fastjson
我就废话不多说了,大家还是直接看代码吧~
package test.refect; public class Student {// 姓名private String name;// 年龄private String age;// 住址private String address; public String getName() {return name;} public void setName(String name) {this.name = name;} public String getAge() {return age;} public void setAge(String age) {this.age = age;} public String getAddress() {return address;} public void setAddress(String address) {this.address = address;} @Overridepublic String toString() {return 'Student [name=' + name + ', age=' + age + ', address=' + address + ']';}public void sayHello(Book book){System.out.println(book.getName());}}
package test.refect; public class Book {private String name; public String getName() {return name;} public void setName(String name) {this.name = name;} }
package test.refect; import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import com.alibaba.fastjson.JSONObject; public class ExecuteWithFastJson { public static <T> void main(String[] args) {// Student str --> Student 主类String str = 'test.refect.Student';Class<?> clazz = null;try {clazz = Class.forName(str);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} // Book实体 str --> Book 参数类String bookStr = 'test.refect.Book';Class<?> bookClazz = null;try {bookClazz = Class.forName(bookStr);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} // json --> Book 将参数类转为JSONOBJECTString bookJson = '{'name':'Java'}'; // 实例化参数类T t = (T) JSONObject.parseObject(bookJson, bookClazz);// 将参数类注入到主类Method method =null;try {method = clazz.getDeclaredMethod('sayHello', bookClazz);} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} // 执行主类try {method.invoke(clazz.newInstance(), t);} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
补充:使用fastjson 进行jsonObject转实体类对象
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.7</version></dependency>
首先引入相关jar包,
假设有一个实体类User
public class User{ private int id; private String name; }
然后通过fastJson进行类型转换
public static void main(String[] args){ String userString = '{'id':1,'name','lz'}'; JSONObject userJson = JSONObject.parseObject(userString); User user = JSON.toJavaObject(userJson,User.class); }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持好吧啦网。如有错误或未考虑完全的地方,望不吝赐教。
相关文章: