目录
以类USER为例:
使用Java的反射机制获取Column的name为“user_name”的类属性值
以类USER为例:
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;@Data
@Table(name = "user_info")
public class User implements Serializable {@Id@Column(name = "id")@GeneratedValue(generator = "JDBC")private Long id;@Column(name = "user_name")private String userName;@Column(name = "user_id")private String userId;@Column(name = "user_age")private String userAge;@Column(name = "user_sex")private String userSex;
private static final long serialVersionUID = 1L;}
使用Java的反射机制获取@Column的name为“user_name”的类属性值
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.persistence.Column;public class FeildToData{public static String getUserNameFiledValue(String targetColumnName,User entity,Class<User> clazz){try{for (Field field : clazz.getDeclaredFields()) {//@Column(name = "user_name")Column columnAnnotation = field.getAnnotation(Column.class);if (columnAnnotation != null && targetColumnName.equals(columnAnnotation.name())) {// 获取字段的getter方法Method getter = clazz.getMethod(getGetterMethodName(field.getName()));// 执行getter方法获取字段值Object fieldValue = getter.invoke(entity);System.out.println("The value of the matched field is: " + fieldValue);if(fieldValue!=null&&String.valueOf(fieldValue).trim().length()>0){return String.valueOf(fieldValue);}else{return null;}}}}catch (Exception e){e.printStackTrace();return null;}return null; }
public static String getGetterMethodName(String fieldName) {return "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);}pulic static void main(String[] args){String targetColumnName = "user_name";User entity = new User();entity.setUserName("菲德勒");entity.setUserId("ETYUN120");entity.setUserSex("Man");Class<User> clazz = User.class;System.out.println(getUserNameFiledValue(targetColumnName,entity,clazz));
}}