MYSQL 之 JDBC(八):增刪改查(六)ReflectionUtils
阿新 • • 發佈:2020-06-28
這裡在網上找了一份ReflectionUtils
package com.litian.jdbc; /** * @author: Li Tian * @contact: [email protected] * @software: IntelliJ IDEA * @file: ReflectionUtils.java * @time: 2020/3/26 18:57 * @desc: |JDBC 查詢得到屬性欄位 反射機制返回到 JavaBean中相同類屬性名的物件中 */ import java.lang.reflect.*; public class ReflectionUtils {View Code/** * 使 filed 變為可訪問 * * @param field */ public static void makeAccessible(Field field) { if (!Modifier.isPublic(field.getModifiers())) { field.setAccessible(true); } } /** * 直接設定物件的屬性,忽略 private/protected 修飾符, 也不經過 setter * * @paramobject * @param fieldName 屬性名稱 * @param value */ public static void setFieldValue(Object object, String fieldName, Object value) { Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]");// 讓 private 元素變得可以訪問,field.setAccessible(); makeAccessible(field); try { field.set(object, value); } catch (IllegalArgumentException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 迴圈向上轉型, 獲取物件的 DeclaredField * * @param object * @param filedName * @return */ public static Field getDeclaredField(Object object, String filedName) { // 一步步的迴圈得到 獲取宣告物件的祖宗類 for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { return superClass.getDeclaredField(filedName); } catch (NoSuchFieldException | SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return null; } /** * 直接讀取物件的屬性值, 忽略 private/protected 修飾符, 也不經過 getter * * @param object * @param fieldName * @return */ public static Object getFieldValue(Object object, String fieldName) { Field field = getDeclaredField(object, fieldName); if (field == null) throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + object + "]"); makeAccessible(field); Object result = null; try { result = field.get(object); } catch (IllegalArgumentException | IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } /** * 迴圈向上轉型, 獲取物件的 DeclaredMethod * * @param object * @param methodName * @param parameterTypes: 指定特定成員方法有過載可能性,必須指定特定的型別變數 * @return */ public static Method getDeclaredMethod(Object object, String methodName, Class<?>[] parameterTypes) { for (Class<?> superClass = object.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { try { //superClass.getMethod(methodName, parameterTypes); return superClass.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { //Method 不在當前類定義, 繼續向上轉型 } //.. } return null; } /** * 直接呼叫物件方法, 而忽略修飾符(private, protected) * * @param object * @param methodName * @param parameterTypes * @param parameters * @return * @throws InvocationTargetException * @throws IllegalArgumentException */ public static Object invokeMethod(Object object, String methodName, Class<?>[] parameterTypes, Object[] parameters) throws InvocationTargetException { Method method = getDeclaredMethod(object, methodName, parameterTypes); if (method == null) throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + object + "]"); method.setAccessible(true); // 使用 method.invoke()方法進行執行 try { method.invoke(object, parameters); } catch (IllegalAccessException | IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return method; } /** * 通過反射, 獲得定義 Class 時宣告的父類的泛型引數的型別 * 如: public EmployeeDao extends BaseDao<Employee, String> * * @param clazz * @return */ public static Class getSuperClassGenricType(Class clazz, int index) { Type genType = clazz.getGenericSuperclass(); // 判定s是否是ParameterType相對應的 if (!(genType instanceof ParameterizedType)) return Object.class; // 強制轉換 獲取超類泛型引數實際型別,返回genType 是類的介面,基本型別或者void Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); if (index >= params.length || index < 0) return Object.class; if (!(params[index] instanceof Class)) return Object.class; return (Class) params[index]; } /** * 通過反射,獲得Class定義中宣告的父類的泛型引數的型別. * eg. * public UserDao extends HibernateDao<User> * * @param clazz The class to introspect * @return the first generic declaration, or Object.class if cannot be determined */ @SuppressWarnings("unchecked") public static <T> Class<T> getSuperClassGenricType(final Class clazz) { return getSuperClassGenricType(clazz, 0); } }
JAVA類屬性
在JAVAEE中,JAVA類的屬性通過getter,setter來定義:get(set)方法:去除get(或set)後,首字母小寫即為該類的屬性。
而之前的屬性,即成員變數稱之為欄位。
操作java類的屬性有一個工具包:beanutils(需要結合logging來用)
BeanUtils.setProperty()
BeanUtils.getProperty()
一般情況下,欄位名和屬性名都一致
通過該工具包可以將之前的ReflectionUtil替換為:BeanUtils.setProperty(entity, propertyName, value);
BeanUtils測試程式碼
package com.litian.jdbc; import org.apache.commons.beanutils.BeanUtils; import java.lang.reflect.InvocationTargetException; /** * @author: Li Tian * @contact: [email protected] * @software: IntelliJ IDEA * @file: BeanUtilsTest.java * @time: 2020/3/27 15:37 * @desc: |測試工具包beanutils */ public class BeanUtilsTest { public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException { // 測試賦值操作 Object obj = new User(); System.out.println(obj); BeanUtils.setProperty(obj, "username", "二哈"); System.out.println(obj); // 測試獲取操作 Object val = BeanUtils.getProperty(obj, "username"); System.out.println(val); } }
————————————————
版權宣告:本文為CSDN博主「李英俊小朋友」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處連結及本宣告。
原文連結:https://blog.csdn.net/qq_21579045/article/details/105386353