Java反射,泛型在Json中的運(yùn)用
最近項(xiàng)目中遇到了Json數(shù)據(jù)自動獲取的功能,不然令人想起java的反射,已經(jīng)很長時(shí)間沒復(fù)習(xí)java了正好一塊連java的這一塊內(nèi)容一起過一遍。java中的反射無疑就相當(dāng)于java開發(fā)者的春天,在眾多的框架中也能看到它的身影,可以在運(yùn)行時(shí)檢查類,接口、變量和方法等信息,可以實(shí)例化調(diào)用方法以及設(shè)置變量值等。本文主要以代碼的形式直接將反射,泛型的運(yùn)用展現(xiàn)出來。
java中的反射首先新建一個(gè)基礎(chǔ)類Author。
package bean;/** * * @author Super~me * Description: 基礎(chǔ)類 * */public class Author {private static String TAG='Big';private String name;private int age;public Author(){}public Author(String name, int age) {super();this.name = name;this.age = age;}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 toString() {return 'Author [name=' + name + ', age=' + age + ']';}private String pMethod(String t){String result=t+' Private Method';return result;}}
然后新建一個(gè)反射類,運(yùn)用反射方法對上面的類進(jìn)行訪問.包括對私有方法的訪問,對私有屬性的訪問等。其中常用的一些方法以及解釋:
//對象的創(chuàng)建public static void reflectNewInstance(){try {Class<?> authorclass=Class.forName(path_reflectfrom);Object object =authorclass.newInstance();Author author=(Author) object;author.setName('周大亨');author.setAge(89);System.out.println('author: '+author.toString());} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//對私有的方法進(jìn)行反射public static void reflectPrivateConstructor(){try {Class<?> authorclass =Class.forName(path_reflectfrom);Constructor<?> declaredConstructor =authorclass.getDeclaredConstructor(String.class,int.class);declaredConstructor.setAccessible(true);Object object=declaredConstructor.newInstance('lida',88);Author author=(Author) object;System.out.println( 'Author: '+author.toString());} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} 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();}}//反射私有的屬性public static void reflectPrivateField(){try {Class<?> authorclass =Class.forName(path_reflectfrom);Object authorobject=authorclass.newInstance();Field field=authorclass.getDeclaredField('TAG');field.setAccessible(true);String tag=(String)field.get(authorobject);System.out.println( 'private field Tag:'+tag);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchFieldException e) {// TODO Auto-generated catch blocke.printStackTrace();}}//反射獲取私有的方法private static void reflectMethod(){try {Class<?> authorclass=Class.forName(path_reflectfrom);Object authorobject=authorclass.newInstance();Method authormethod=authorclass.getDeclaredMethod('pMethod', String.class);authormethod.setAccessible(true);String string=(String)authormethod.invoke(authorobject, TAG);System.out.println( 'private Method: '+string);} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (NoSuchMethodException 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();}}
通過控制臺打印以上信息:查看運(yùn)用結(jié)果
ReflectClass.reflectNewInstance();ReflectClass.reflectPrivateField();ReflectClass.reflectPrivateConstructor();ReflectClass.reflectMethod();
運(yùn)行結(jié)果:
對于泛型其實(shí)很好理解,通俗點(diǎn)講就是我們將類型也當(dāng)成了參數(shù)進(jìn)行傳值,這樣做代碼的安全性很大的被提升了,也為較大的優(yōu)化帶來可能。泛型可以使編譯器知道一個(gè)對象的限定類型是什么,這樣編譯器就可以在一個(gè)高的程度上驗(yàn)證這個(gè)類型消除了強(qiáng)制類型轉(zhuǎn)換 使得代碼可讀性好,減少了很多出錯(cuò)的機(jī)會。但是也要記住泛型的規(guī)范,比如靜態(tài)的變量和方法不能引用泛型變量,我們也不能利用instanceof等方法對泛型的類型進(jìn)行判斷,當(dāng)然這樣做也毫無意義,重要的一點(diǎn)是泛型類不能繼承Exception或者Throwable。泛型的繼承中,不論子類是否為泛型類,所繼承和實(shí)現(xiàn)的父類接口都需要被指定。常用的泛型類型變量:E:元素(Element)K:關(guān)鍵字(Key)N:數(shù)字(Number)T:類型(Type)V:值(Value)另外泛型界定的概念主要是指對泛型類型進(jìn)行一個(gè)限定。比如:
public static <T extends String> T add(T str1, T str2) { return '';}
利用泛型和反射實(shí)現(xiàn)對json數(shù)據(jù)的保存//利用反射獲取json數(shù)據(jù)到j(luò)ava類 private static void getJson(){ try { String json = '{'name':'Miss王','age':79}'; JSONObject source=JSONObject.parseObject(json); Class<?> aClass = Class.forName('bean.Author'); Object obj = aClass.newInstance(); Field[] declaredFields = aClass.getDeclaredFields(); for (Field field : declaredFields) {field.setAccessible(true);System.out.println(source.getString(field.getName()));if (field.getGenericType().toString().equals(String.class.toString())) { field.set(obj, source.getString(field.getName()));} else if (field.getGenericType().toString().equals(int.class.toString())) { field.set(obj, source.getInteger(field.getName()));} } Author author = (Author) obj; System.out.print(author); } catch (Exception e) { e.printStackTrace(); } }
我們想把以上的實(shí)現(xiàn)封裝起來,這時(shí)就用了泛型。
//泛型+反射實(shí)現(xiàn)json數(shù)據(jù)讀取到j(luò)ava類 public static <T> T getJsonClass(String json, Class<T> beanclass) { try { JSONObject jsonObject = JSONObject.parseObject(json); Object obj = beanclass.newInstance(); //拿到所以元素 Field[] declaredFields = beanclass.getDeclaredFields(); for (Field field : declaredFields) {field.setAccessible(true); if (field.getGenericType().toString().equals(String.class.toString())) {String value=jsonObject.getString(field.getName()); if(value!=null){ field.set(obj,value); System.out.println(value); }} else if (field.getGenericType().toString().equals(int.class.toString())) { if(jsonObject.getInteger(field.getName())!=null) field.set(obj,jsonObject.getInteger(field.getName())); } } return (T) obj; } catch (Exception e) { e.printStackTrace(); } return null; }
調(diào)用實(shí)現(xiàn):
public static void main(String[] args) {// TODO Auto-generated method stubString json = '{'name':'李先生','age':82}'; //ReflectJson.getJson();//解析json然后換成實(shí)體類Author author=getJsonClass(json, Author.class);System.out.print( author.toString());}
運(yùn)行結(jié)果:
以上就是Java反射,泛型在Json中的運(yùn)用的詳細(xì)內(nèi)容,更多關(guān)于Java反射,泛型的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. java反射方式創(chuàng)建代碼詳解2. java反射獲取包下所有類的操作3. 利用Java反射機(jī)制實(shí)現(xiàn)對象相同字段的復(fù)制操作4. 使用Java反射模擬實(shí)現(xiàn)Spring的IoC容器的操作5. java反射之Method的invoke方法實(shí)現(xiàn)教程詳解6. Java反射技術(shù)原理與用法實(shí)例分析7. java反射機(jī)制給實(shí)體類相同字段自動賦值實(shí)例8. Java反射獲取實(shí)例的速度對比分析9. Java反射框架Reflections示例詳解10. Java反射技術(shù)詳解及實(shí)例解析
