java.lang.reflect.Method 中getWriteMethod() 的使用方法

本文介绍了一种利用反射机制中的getWriteMethod方法来为Java Bean的属性赋值的方法。通过创建一个简单的Java Bean类,并使用Introspector获取BeanInfo及PropertyDescriptor,最终实现了动态调用setter方法为Bean的属性赋值。

使用getWriteMethod() 为类的属性赋值。

一、普通类如下:

public class MyBean {
	private String id = null;
	private String userName = null;
	
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	
}

 

二、测试类如下:

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MethodWrite {
	
	private MyBean beanObj = null;
	
	private BeanInfo bBeanObjInfo = null;
	
	public void TestMethodInvoke(){
		Map userMap = new HashMap();
		userMap.put("id", "1001");
		userMap.put("userName", "isoftstone");
		
		try{
			//实例化一个Bean
			beanObj = new MyBean();
			//依据Bean产生一个相关的BeanInfo类
			bBeanObjInfo = Introspector.getBeanInfo(beanObj.getClass());
			
			PropertyDescriptor[] propertyDesc = bBeanObjInfo.getPropertyDescriptors();
			for (int i = 0; i < propertyDesc.length; i++) {
				if (propertyDesc[i].getName().compareToIgnoreCase("class")==0) continue;
				//System.out.print(propertyDesc[i].getName());
				String strValue = (String)userMap.get((String)propertyDesc[i].getName());
				//System.out.println(strValue);
				
				if(strValue != null){
					Object[] oParam = new Object[]{};
					Method mr = propertyDesc[i].getWriteMethod();
					if( mr != null){
						oParam = new String[]{(strValue)};
						try{
							//注意这里的参数。
							mr.invoke(beanObj, oParam);
						}catch(IllegalArgumentException iea){
							System.out.println("参数错误。");
							iea.printStackTrace();
						}
						
					}
				}
				
			}
			
			System.out.println(beanObj.getId());
			System.out.println(beanObj.getUserName());
			
		}catch(IntrospectionException e){
			System.out.println("Java Bean 内省异常。");
		}catch(IllegalAccessException ia){
			System.out.println("参数异常。");
			ia.printStackTrace();
		}catch(InvocationTargetException ie){
			System.out.println("invode异常。");
			ie.printStackTrace();
		}
		
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new MethodWrite().TestMethodInvoke();
	}

}

 

package com.sjsemi.util; import com.sjsemi.common.utils.FormatUtils; import lombok.var; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.beans.Introspector; import java.lang.reflect.Field; import java.util.stream.Collectors; import javax.persistence.Column; import javax.persistence.Table; import javax.persistence.Id; public class BeanMapper { /** * 动态映射数据库记录到目标对象 * * @param target 目标对象 * @param record 数据库记录 */ public static void mapFields(Object target, Map<String, Object> record) { try { var beanInfo = Introspector.getBeanInfo(target.getClass()); for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) { if ("class".equals(pd.getName())) continue; var setter = pd.getWriteMethod(); if (setter == null) continue; // 获取字段对象 Field field = null; try { field = target.getClass().getDeclaredField(pd.getName()); } catch (NoSuchFieldException e) { continue; // 跳过不存在的字段 } // 检查@Column注解 Column columnAnnotation = field.getAnnotation(Column.class); String columnName; if (columnAnnotation != null) { columnName = columnAnnotation.name(); // 使用注解指定的列名 } else { columnName = toColumnName(pd.getName()); // 默认转换 } // 获取值并转换 var value = record.get(columnName); var convertedValue = convertValue(value, pd.getPropertyType()); if (convertedValue != null) { setter.invoke(target, convertedValue); } } } catch (Exception e) { e.printStackTrace(); } } /** * 将对象转换为参数Map */ public static Map<String, Object> toParamMap(Object entity) { Map<String, Object> paramMap = new HashMap<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(entity.getClass()); for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) { if ("class".equals(pd.getName())) continue; Method readMethod = pd.getReadMethod(); if (readMethod == null) continue; // 获取对应的字段(Field) Field field = null; try { field = entity.getClass().getDeclaredField(pd.getName()); } catch (NoSuchFieldException e) { continue; // 如果找不到字段,跳过 } // 检查是否有@Column注解 Column columnAnnotation = field.getAnnotation(Column.class); String key; if (columnAnnotation != null) { key = columnAnnotation.name(); // 使用列名作为键 } else { key = pd.getName(); // 如果没有注解,使用属性名 } Object value = readMethod.invoke(entity); paramMap.put(key, value); } } catch (Exception e) { throw new RuntimeException(e); } return paramMap; } /** * 类型转换工具 */ private static Object convertValue(Object value, Class<?> targetType) { if (value == null) { if (targetType == String.class) { return ""; } else if (targetType == Integer.TYPE || targetType == Integer.class) { return 0; } else if (targetType == Boolean.TYPE || targetType == Boolean.class) { return false; } return null; } if (targetType == String.class) { return FormatUtils.parseString(value); } else if (targetType == Integer.TYPE || targetType == Integer.class) { return FormatUtils.parseInteger(value); } return value; } /** * 将属性名转换为数据库列名 */ private static String toColumnName(String propertyName) { if (propertyName == null || propertyName.isEmpty()) { return propertyName; } return propertyName; } public static String getTableName(Class<?> entityType) { Table table = entityType.getAnnotation(Table.class); if (table != null) { return table.name(); } return entityType.getSimpleName().toLowerCase() + "s"; } public static List<String> getColumnNames(Class<?> entityType) { try { PropertyDescriptor[] pds = Introspector.getBeanInfo(entityType).getPropertyDescriptors(); return Arrays.stream(pds) .filter(pd -> !"class".equals(pd.getName())) .map(pd -> toColumnName(pd.getName())) .collect(Collectors.toList()); } catch (IntrospectionException e) { throw new RuntimeException(e); } } public static List<String> getPrimaryKeys(Class<?> entityType) { List<String> keys = new ArrayList<>(); for (Field field : entityType.getDeclaredFields()) { if (field.isAnnotationPresent(Id.class)) { // 检查 @Id 注解 Column column = field.getAnnotation(Column.class); String columnName = column != null && !column.name().isEmpty() ? column.name() : toColumnName(field.getName()); keys.add(columnName); } } return keys; } /** * 生成INSERT语句 */ public static String buildInsertSql(Class<?> entityType) { String tableName = getTableName(entityType); List<String> columns = getColumnNames(entityType); String columnsStr = String.join(", ", columns); String paramsStr = columns.stream().map(c -> ":" + c).collect(Collectors.joining(", ")); return String.format("INSERT INTO %s (%s) VALUES (%s)", tableName, columnsStr, paramsStr); } /** * 生成UPDATE语句 */ public static String buildUpdateSql(Class<?> entityType) { String tableName = getTableName(entityType); List<String> columns = getColumnNames(entityType); List<String> primaryKeys = getPrimaryKeys(entityType); // 过滤掉主键字段,仅保留非主键字段在 SET 子句 List<String> nonPrimaryKeyColumns = columns.stream() .filter(c -> !primaryKeys.contains(c)) .collect(Collectors.toList()); String setClause = nonPrimaryKeyColumns.stream() .map(c -> c + " = :" + c) .collect(Collectors.joining(", ")); String whereClause = primaryKeys.stream() .map(c -> c + " = :" + c) .collect(Collectors.joining(" AND ")); return String.format("UPDATE %s SET %s WHERE %s", tableName, setClause, whereClause); } /** * 生成DELETE语句 */ public static String buildDeleteSql(Class<?> entityType) { String tableName = getTableName(entityType); List<String> primaryKeys = getPrimaryKeys(entityType); List<String> whereClauses = primaryKeys.stream().map(c -> c + " = :" + c).collect(Collectors.toList()); String whereClause = String.join(" AND ", whereClauses); return String.format("DELETE FROM %s WHERE %s", tableName, whereClause); } /** * 生成基础SELECT语句 */ public static String buildSelectSql(Class<?> entityType) { String tableName = getTableName(entityType); List<String> columns = getColumnNames(entityType); String columnsStr = String.join(", ", columns); return String.format("SELECT %s FROM %s", columnsStr, tableName); } /** * 生成带WHERE条件的COUNT语句 */ public static String buildCountSql(Class<?> entityType, String whereClause) { return String.format("SELECT COUNT(*) FROM %s WHERE %s", getTableName(entityType), whereClause); } /** * 生成分页SQL */ public static String buildPagedSql(String innerSql) { return String.format( "SELECT t.* FROM (SELECT rownum row_num, t.* FROM (%s) t WHERE rownum <= :END_INDEX) t WHERE t.row_num >= :START_INDEX", innerSql ); } /** * 根据实体对象生成WHERE条件 */ public static String buildWhereClause(Class<?> entityType, Object entity) { try { PropertyDescriptor[] pds = Introspector.getBeanInfo(entityType).getPropertyDescriptors(); List<String> conditions = Arrays.stream(pds) .filter(pd -> !"class".equals(pd.getName())) .map(pd -> { String propertyName = pd.getName(); try { // 获取字段并检查@Column注解 Field field = entityType.getDeclaredField(propertyName); Column column = field.getAnnotation(Column.class); String columnName = column != null ? column.name() : toColumnName(propertyName); // 获取属性值并判断是否有效 Object value = pd.getReadMethod().invoke(entity); if (value == null) return null; if (value instanceof String && ((String) value).trim().isEmpty()) return null; // 生成条件表达式 return columnName + " = :" + columnName; } catch (NoSuchFieldException | IllegalAccessException | InvocationTargetException e) { return null; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); // 拼接最终的WHERE条件 return conditions.isEmpty() ? "1=1" : "1=1 AND " + String.join(" AND ", conditions); } catch (Exception e) { throw new RuntimeException("Failed to build where clause", e); } } /** * 通用方法:去除对象中所有 String 类型字段的左右空格和换行符 * @param obj 待处理的对象 */ public static void objectTrim(Object obj) { if (obj == null) { return; } Class<?> clazz = obj.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (field.getType() == String.class) { field.setAccessible(true); try { String value = (String) field.get(obj); if (value != null) { // 使用正则去除左右空格和换行符 String cleaned = value.replaceAll("^\\s+|\\s+$", ""); field.set(obj, cleaned); } } catch (IllegalAccessException e) { e.printStackTrace(); } } } } } 单签是这样的
09-11
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值