com.cntool.core.method.UseMethods Maven / Gradle / Ivy
The newest version!
package com.cntool.core.method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
/**
* @program: practice
* @description: 使用指定属性名的get、set方法
* @author: ID-Tang
* @create: 2022-04-14 10:45
* @copyright: Copyright (c) [2022] [ID-tang]
* [cntool] is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
**/
public class UseMethods {
/**
* 反射获取get方法
*
* @param ob 对象
* @param name 字段名
* @return 该字段名的值
*/
public static Object getGetMethod(Object ob, String name) {
Method[] m = ob.getClass().getMethods();
for (Method method : m) {
if (("get" + name).toLowerCase().equals(method.getName().toLowerCase())) {
try {
return method.invoke(ob);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
return null;
}
/**
* 根据属性,拿到set方法,并把值set到对象中
*
* @param obj 对象
* @param clazz 对象的class
* @param filedName 需要设置值得属性
* @param typeClass 属性对应的类型
* @param value 需要设置的值
*/
public static void setValue(Object obj, Class> clazz, String filedName, Class> typeClass, Object value) {
String methodName = "set" + filedName.substring(0, 1).toUpperCase() + filedName.substring(1);
try {
Method method = clazz.getDeclaredMethod(methodName, typeClass);
method.invoke(obj, getClassTypeValue(typeClass, value));
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 通过class类型获取获取对应类型的值
*
* @param typeClass class类型
* @param value 值
* @return Object
*/
private static Object getClassTypeValue(Class> typeClass, Object value) {
if (typeClass == int.class || value instanceof Integer) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == short.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == byte.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == double.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == long.class) {
if (null == value) {
return 0;
}
return value;
} else if (typeClass == String.class) {
if (null == value) {
return "";
}
return value;
} else if (typeClass == boolean.class) {
if (null == value) {
return true;
}
return value;
} else if (typeClass == BigDecimal.class) {
if (null == value) {
return new BigDecimal(0);
}
return new BigDecimal(value + "");
} else {
return typeClass.cast(value);
}
}
}