Java 八大基本型別各有對應的 Class 常數:
Integer.TYPE 代表 intLong.TYPE 代表 longBoolean.TYPE 代表 boolean此設計使得「未知 JavaBean 的通用屬性填充」成為可能:透過 PropertyDescriptor 取得寫入方法的參數型別,再依 Class 物件判斷轉換策略。
Object bean = ...; // 目標 Bean
BeanInfo bi = Introspector.getBeanInfo(bean.getClass());
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String name = pd.getName();
String value = request.getParameter(name); // 來自 HTTP 請求
if (value != null) {
Method setter = pd.getWriteMethod();
Class> paramType = setter.getParameterTypes()[0];
Object converted = convert(value, paramType);
setter.invoke(bean, converted);
}
}
public Object convert(Object value, Class> type) {
String typeName = type.getName();
if ("java.lang.String".equals(typeName)) {
return value.toString();
} else if ("java.lang.Long".equals(typeName) || type == Long.TYPE) {
return Long.valueOf(value.toString());
} else if ("java.lang.Integer".equals(typeName) || type == Integer.TYPE) {
return Integer.valueOf(value.toString());
} else if ("java.lang.Boolean".equals(typeName) || type == Boolean.TYPE) {
return Boolean.valueOf(value.toString());
} else if ("java.lang.Double".equals(typeName) || type == Double.TYPE) {
return Double.valueOf(value.toString());
} // ... 其他型別
throw new IllegalArgumentException("Unsupported type: " + typeName);
}
Java 8+ 可結合 MethodHandles、VarHandle 提升效能;Jackson、Gson 等序列化庫已內建高效能反射快取與型別適配,生產環境優先採用成熟庫。