增加车辆报文中故障更改

new-master
DongZeLiang 2023-11-29 16:38:10 +08:00
parent 03b635db32
commit a9246688b2
6 changed files with 1256 additions and 0 deletions

View File

@ -89,6 +89,11 @@
<version>1.2.73</version>
</dependency>
<!--常用工具类 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -7,6 +7,8 @@ import com.muyu.domain.req.MsgReq;
import com.muyu.domain.req.VehicleInstanceListReq;
import com.muyu.domain.resp.VehicleInstanceResp;
import com.muyu.service.VehicleInstanceService;
import com.muyu.vehicle.core.LocalContainer;
import com.muyu.vehicle.model.VehicleData;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@ -37,6 +39,16 @@ public class VehicleInstanceController {
return Result.success(list);
}
/**
* VIN
* @param vin VIN
* @return
*/
@GetMapping("/data/{vin}")
public Result<VehicleData> getVehicleData(@PathVariable("vin") String vin){
return Result.success(LocalContainer.getVehicleInstance(vin).getVehicleData());
}
/**
*
* @param vin vin
@ -89,4 +101,12 @@ public class VehicleInstanceController {
this.vehicleInstanceService.gear(gearReq);
return Result.success();
}
@PutMapping("/status/{vin}/{statusKey}/{statusValue}")
public Result<String> editStatus(@PathVariable("statusKey") String statusKey,
@PathVariable("vin") String vin,
@PathVariable("statusValue") Integer statusValue){
this.vehicleInstanceService.editStatus(vin, statusKey, statusValue);
return Result.success();
}
}

View File

@ -60,4 +60,13 @@ public interface VehicleInstanceService {
* @param gearReq
*/
void gear (GearReq gearReq);
/**
*
* @param vin vin
* @param statusKey
* @param statusValue
*/
void editStatus (String vin, String statusKey, Integer statusValue);
}

View File

@ -11,6 +11,7 @@ import com.muyu.domain.resp.VehicleInstanceResp;
import com.muyu.service.PositionRouteService;
import com.muyu.service.VehicleInstanceService;
import com.muyu.utils.MD5Util;
import com.muyu.utils.ReflectUtils;
import com.muyu.vehicle.VehicleInstance;
import com.muyu.vehicle.api.ClientAdmin;
import com.muyu.vehicle.api.req.VehicleConnectionReq;
@ -165,4 +166,18 @@ public class VehicleInstanceServiceImpl implements VehicleInstanceService {
vehicleInstance.setGear(gearReq.getGear());
}
/**
*
*
* @param vin vin
* @param statusKey
* @param statusValue
*/
@Override
public void editStatus (String vin, String statusKey, Integer statusValue) {
VehicleInstance vehicleInstance = LocalContainer.getVehicleInstance(vin);
VehicleData vehicleData = vehicleInstance.getVehicleData();
ReflectUtils.invokeSetter(vehicleData, statusKey, statusValue);
}
}

View File

@ -0,0 +1,893 @@
package com.muyu.utils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.Set;
/**
*
*
* @author ruoyi
*/
public class Convert {
/**
* <br>
* null<br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static String toStr (Object value, String defaultValue) {
if (null == value) {
return defaultValue;
}
if (value instanceof String) {
return (String) value;
}
return value.toString();
}
/**
* <br>
* <code>null</code><code>null</code><br>
*
*
* @param value
*
* @return
*/
public static String toStr (Object value) {
return toStr(value, null);
}
/**
* <br>
* null<br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Character toChar (Object value, Character defaultValue) {
if (null == value) {
return defaultValue;
}
if (value instanceof Character) {
return (Character) value;
}
final String valueStr = toStr(value, null);
return StringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0);
}
/**
* <br>
* <code>null</code><code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Character toChar (Object value) {
return toChar(value, null);
}
/**
* byte<br>
* <code>null</code><br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Byte toByte (Object value, Byte defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Byte) {
return (Byte) value;
}
if (value instanceof Number) {
return ((Number) value).byteValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Byte.parseByte(valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* byte<br>
* <code>null</code><code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Byte toByte (Object value) {
return toByte(value, null);
}
/**
* Short<br>
* <code>null</code><br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Short toShort (Object value, Short defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Short) {
return (Short) value;
}
if (value instanceof Number) {
return ((Number) value).shortValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Short.parseShort(valueStr.trim());
} catch (Exception e) {
return defaultValue;
}
}
/**
* Short<br>
* <code>null</code><code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Short toShort (Object value) {
return toShort(value, null);
}
/**
* Number<br>
* <br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Number toNumber (Object value, Number defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Number) {
return (Number) value;
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return NumberFormat.getInstance().parse(valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Number<br>
* <code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Number toNumber (Object value) {
return toNumber(value, null);
}
/**
* int<br>
* <br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Integer toInt (Object value, Integer defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Integer) {
return (Integer) value;
}
if (value instanceof Number) {
return ((Number) value).intValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Integer.parseInt(valueStr.trim());
} catch (Exception e) {
return defaultValue;
}
}
/**
* int<br>
* <code>null</code><code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Integer toInt (Object value) {
return toInt(value, null);
}
/**
* Integer<br>
*
* @param str
*
* @return
*/
public static Integer[] toIntArray (String str) {
return toIntArray(",", str);
}
/**
* Long<br>
*
* @param str
*
* @return
*/
public static Long[] toLongArray (String str) {
return toLongArray(",", str);
}
/**
* Integer<br>
*
* @param split
* @param split
*
* @return
*/
public static Integer[] toIntArray (String split, String str) {
if (StringUtils.isEmpty(str)) {
return new Integer[]{};
}
String[] arr = str.split(split);
final Integer[] ints = new Integer[arr.length];
for (int i = 0 ; i < arr.length ; i++) {
final Integer v = toInt(arr[i], 0);
ints[i] = v;
}
return ints;
}
/**
* Long<br>
*
* @param split
* @param str
*
* @return
*/
public static Long[] toLongArray (String split, String str) {
if (StringUtils.isEmpty(str)) {
return new Long[]{};
}
String[] arr = str.split(split);
final Long[] longs = new Long[arr.length];
for (int i = 0 ; i < arr.length ; i++) {
final Long v = toLong(arr[i], null);
longs[i] = v;
}
return longs;
}
/**
* String<br>
*
* @param str
*
* @return
*/
public static String[] toStrArray (String str) {
return toStrArray(",", str);
}
/**
* String<br>
*
* @param split
* @param split
*
* @return
*/
public static String[] toStrArray (String split, String str) {
return str.split(split);
}
/**
* long<br>
* <br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Long toLong (Object value, Long defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Long) {
return (Long) value;
}
if (value instanceof Number) {
return ((Number) value).longValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
// 支持科学计数法
return new BigDecimal(valueStr.trim()).longValue();
} catch (Exception e) {
return defaultValue;
}
}
/**
* long<br>
* <code>null</code><code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Long toLong (Object value) {
return toLong(value, null);
}
/**
* double<br>
* <br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Double toDouble (Object value, Double defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Double) {
return (Double) value;
}
if (value instanceof Number) {
return ((Number) value).doubleValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
// 支持科学计数法
return new BigDecimal(valueStr.trim()).doubleValue();
} catch (Exception e) {
return defaultValue;
}
}
/**
* double<br>
* <code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Double toDouble (Object value) {
return toDouble(value, null);
}
/**
* Float<br>
* <br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Float toFloat (Object value, Float defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Float) {
return (Float) value;
}
if (value instanceof Number) {
return ((Number) value).floatValue();
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Float.parseFloat(valueStr.trim());
} catch (Exception e) {
return defaultValue;
}
}
/**
* Float<br>
* <code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Float toFloat (Object value) {
return toFloat(value, null);
}
/**
* boolean<br>
* Stringtruefalseyesokno1,0 <br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static Boolean toBool (Object value, Boolean defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof Boolean) {
return (Boolean) value;
}
String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
valueStr = valueStr.trim().toLowerCase();
switch (valueStr) {
case "true":
case "yes":
case "ok":
case "1":
return true;
case "false":
case "no":
case "0":
return false;
default:
return defaultValue;
}
}
/**
* boolean<br>
* <code>null</code><br>
*
*
* @param value
*
* @return
*/
public static Boolean toBool (Object value) {
return toBool(value, null);
}
/**
* Enum<br>
* <br>
*
* @param clazz EnumClass
* @param value
* @param defaultValue
*
* @return Enum
*/
public static <E extends Enum<E>> E toEnum (Class<E> clazz, Object value, E defaultValue) {
if (value == null) {
return defaultValue;
}
if (clazz.isAssignableFrom(value.getClass())) {
@SuppressWarnings("unchecked")
E myE = (E) value;
return myE;
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return Enum.valueOf(clazz, valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* Enum<br>
* <code>null</code><br>
*
* @param clazz EnumClass
* @param value
*
* @return Enum
*/
public static <E extends Enum<E>> E toEnum (Class<E> clazz, Object value) {
return toEnum(clazz, value, null);
}
/**
* BigInteger<br>
* <br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static BigInteger toBigInteger (Object value, BigInteger defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof BigInteger) {
return (BigInteger) value;
}
if (value instanceof Long) {
return BigInteger.valueOf((Long) value);
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return new BigInteger(valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* BigInteger<br>
* <code>null</code><br>
*
*
* @param value
*
* @return
*/
public static BigInteger toBigInteger (Object value) {
return toBigInteger(value, null);
}
/**
* BigDecimal<br>
* <br>
*
*
* @param value
* @param defaultValue
*
* @return
*/
public static BigDecimal toBigDecimal (Object value, BigDecimal defaultValue) {
if (value == null) {
return defaultValue;
}
if (value instanceof BigDecimal) {
return (BigDecimal) value;
}
if (value instanceof Long) {
return new BigDecimal((Long) value);
}
if (value instanceof Double) {
return BigDecimal.valueOf((Double) value);
}
if (value instanceof Integer) {
return new BigDecimal((Integer) value);
}
final String valueStr = toStr(value, null);
if (StringUtils.isEmpty(valueStr)) {
return defaultValue;
}
try {
return new BigDecimal(valueStr);
} catch (Exception e) {
return defaultValue;
}
}
/**
* BigDecimal<br>
* <br>
*
*
* @param value
*
* @return
*/
public static BigDecimal toBigDecimal (Object value) {
return toBigDecimal(value, null);
}
/**
* <br>
* 1ByteByteBuffer 2Arrays.toString
*
* @param obj
*
* @return
*/
public static String utf8Str (Object obj) {
return str(obj, "utf-8");
}
/**
* <br>
* 1ByteByteBuffer 2Arrays.toString
*
* @param obj
* @param charsetName
*
* @return
*/
public static String str (Object obj, String charsetName) {
return str(obj, Charset.forName(charsetName));
}
/**
* <br>
* 1ByteByteBuffer 2Arrays.toString
*
* @param obj
* @param charset
*
* @return
*/
public static String str (Object obj, Charset charset) {
if (null == obj) {
return null;
}
if (obj instanceof String) {
return (String) obj;
} else if (obj instanceof byte[]) {
return str((byte[]) obj, charset);
} else if (obj instanceof Byte[]) {
byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj);
return str(bytes, charset);
} else if (obj instanceof ByteBuffer) {
return str((ByteBuffer) obj, charset);
}
return obj.toString();
}
/**
* byte
*
* @param bytes byte
* @param charset
*
* @return
*/
public static String str (byte[] bytes, String charset) {
return str(bytes, StringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset));
}
/**
*
*
* @param data
* @param charset
*
* @return
*/
public static String str (byte[] data, Charset charset) {
if (data == null) {
return null;
}
if (null == charset) {
return new String(data);
}
return new String(data, charset);
}
/**
* byteBuffer
*
* @param data
* @param charset 使
*
* @return
*/
public static String str (ByteBuffer data, String charset) {
if (data == null) {
return null;
}
return str(data, Charset.forName(charset));
}
/**
* byteBuffer
*
* @param data
* @param charset 使
*
* @return
*/
public static String str (ByteBuffer data, Charset charset) {
if (null == charset) {
charset = Charset.defaultCharset();
}
return charset.decode(data).toString();
}
// ----------------------------------------------------------------------- 全角半角转换
/**
*
*
* @param input String.
*
* @return .
*/
public static String toSBC (String input) {
return toSBC(input, null);
}
/**
*
*
* @param input String
* @param notConvertSet
*
* @return .
*/
public static String toSBC (String input, Set<Character> notConvertSet) {
char[] c = input.toCharArray();
for (int i = 0 ; i < c.length ; i++) {
if (null != notConvertSet && notConvertSet.contains(c[i])) {
// 跳过不替换的字符
continue;
}
if (c[i] == ' ') {
c[i] = '\u3000';
} else if (c[i] < '\177') {
c[i] = (char) (c[i] + 65248);
}
}
return new String(c);
}
/**
*
*
* @param input String.
*
* @return
*/
public static String toDBC (String input) {
return toDBC(input, null);
}
/**
*
*
* @param text
* @param notConvertSet
*
* @return
*/
public static String toDBC (String text, Set<Character> notConvertSet) {
char[] c = text.toCharArray();
for (int i = 0 ; i < c.length ; i++) {
if (null != notConvertSet && notConvertSet.contains(c[i])) {
// 跳过不替换的字符
continue;
}
if (c[i] == '\u3000') {
c[i] = ' ';
} else if (c[i] > '\uFF00' && c[i] < '\uFF5F') {
c[i] = (char) (c[i] - 65248);
}
}
String returnString = new String(c);
return returnString;
}
/**
*
*
* @param n
*
* @return
*/
public static String digitUppercase (double n) {
String[] fraction = {"角", "分"};
String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
String[][] unit = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}};
String head = n < 0 ? "负" : "";
n = Math.abs(n);
String s = "";
for (int i = 0 ; i < fraction.length ; i++) {
s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", "");
}
if (s.length() < 1) {
s = "整";
}
int integerPart = (int) Math.floor(n);
for (int i = 0 ; i < unit[0].length && integerPart > 0 ; i++) {
String p = "";
for (int j = 0 ; j < unit[1].length && n > 0 ; j++) {
p = digit[integerPart % 10] + unit[1][j] + p;
integerPart = integerPart / 10;
}
s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s;
}
return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整");
}
}

View File

@ -0,0 +1,314 @@
package com.muyu.utils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.*;
/**
* . getter/setter, 访, , Class, AOP.
*
* @author ruoyi
*/
@SuppressWarnings("rawtypes")
public class ReflectUtils {
private static final String SETTER_PREFIX = "set";
private static final String GETTER_PREFIX = "get";
private static final String CGLIB_CLASS_SEPARATOR = "$$";
private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class);
/**
* Getter.
* ..
*/
@SuppressWarnings("unchecked")
public static <E> E invokeGetter (Object obj, String propertyName) {
Object object = obj;
for (String name : StringUtils.split(propertyName, ".")) {
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
}
return (E) object;
}
/**
* Setter,
* ..
*/
public static <E> void invokeSetter (Object obj, String propertyName, E value) {
Object object = obj;
String[] names = StringUtils.split(propertyName, ".");
for (int i = 0 ; i < names.length ; i++) {
if (i < names.length - 1) {
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{});
} else {
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
invokeMethodByName(object, setterMethodName, new Object[]{value});
}
}
}
/**
* , private/protected, getter.
*/
@SuppressWarnings("unchecked")
public static <E> E getFieldValue (final Object obj, final String fieldName) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
return null;
}
E result = null;
try {
result = (E) field.get(obj);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}", e.getMessage());
}
return result;
}
/**
* , private/protected, setter.
*/
public static <E> void setFieldValue (final Object obj, final String fieldName, final E value) {
Field field = getAccessibleField(obj, fieldName);
if (field == null) {
// throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 ");
return;
}
try {
field.set(obj, value);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常: {}", e.getMessage());
}
}
/**
* , private/protected.
* 使getAccessibleMethod()Method.
* +
*/
@SuppressWarnings("unchecked")
public static <E> E invokeMethod (final Object obj, final String methodName, final Class<?>[] parameterTypes,
final Object[] args) {
if (obj == null || methodName == null) {
return null;
}
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
if (method == null) {
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
return null;
}
try {
return (E) method.invoke(obj, args);
} catch (Exception e) {
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
throw convertReflectionExceptionToUnchecked(msg, e);
}
}
/**
* , private/protected
* 使getAccessibleMethodByName()Method.
*
*/
@SuppressWarnings("unchecked")
public static <E> E invokeMethodByName (final Object obj, final String methodName, final Object[] args) {
Method method = getAccessibleMethodByName(obj, methodName, args.length);
if (method == null) {
// 如果为空不报错,直接返回空。
logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 ");
return null;
}
try {
// 类型转换(将参数数据类型转换为目标方法参数类型)
Class<?>[] cs = method.getParameterTypes();
for (int i = 0 ; i < cs.length ; i++) {
if (args[i] != null && !args[i].getClass().equals(cs[i])) {
if (cs[i] == String.class) {
args[i] = Convert.toStr(args[i]);
if (StringUtils.endsWith((String) args[i], ".0")) {
args[i] = StringUtils.substringBefore((String) args[i], ".0");
}
} else if (cs[i] == Integer.class) {
args[i] = Convert.toInt(args[i]);
} else if (cs[i] == Long.class) {
args[i] = Convert.toLong(args[i]);
} else if (cs[i] == Double.class) {
args[i] = Convert.toDouble(args[i]);
} else if (cs[i] == Float.class) {
args[i] = Convert.toFloat(args[i]);
} else if (cs[i] == boolean.class || cs[i] == Boolean.class) {
args[i] = Convert.toBool(args[i]);
}
}
}
return (E) method.invoke(obj, args);
} catch (Exception e) {
String msg = "method: " + method + ", obj: " + obj + ", args: " + args + "";
throw convertReflectionExceptionToUnchecked(msg, e);
}
}
/**
* , DeclaredField, 访.
* Object, null.
*/
public static Field getAccessibleField (final Object obj, final String fieldName) {
// 为空不报错。直接返回 null
if (obj == null) {
return null;
}
Validate.notBlank(fieldName, "fieldName can't be blank");
for (Class<?> superClass = obj.getClass() ; superClass != Object.class ; superClass = superClass.getSuperclass()) {
try {
Field field = superClass.getDeclaredField(fieldName);
makeAccessible(field);
return field;
} catch (NoSuchFieldException e) {
continue;
}
}
return null;
}
/**
* , DeclaredMethod,访.
* Object, null.
* +
* . 使Method,Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethod (final Object obj, final String methodName,
final Class<?>... parameterTypes) {
// 为空不报错。直接返回 null
if (obj == null) {
return null;
}
Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass() ; searchType != Object.class ; searchType = searchType.getSuperclass()) {
try {
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
makeAccessible(method);
return method;
} catch (NoSuchMethodException e) {
continue;
}
}
return null;
}
/**
* , DeclaredMethod,访.
* Object, null.
*
* . 使Method,Method.invoke(Object obj, Object... args)
*/
public static Method getAccessibleMethodByName (final Object obj, final String methodName, int argsNum) {
// 为空不报错。直接返回 null
if (obj == null) {
return null;
}
Validate.notBlank(methodName, "methodName can't be blank");
for (Class<?> searchType = obj.getClass() ; searchType != Object.class ; searchType = searchType.getSuperclass()) {
Method[] methods = searchType.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) {
makeAccessible(method);
return method;
}
}
}
return null;
}
/**
* private/protectedpublicJDKSecurityManager
*/
public static void makeAccessible (Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible()) {
method.setAccessible(true);
}
}
/**
* private/protectedpublicJDKSecurityManager
*/
public static void makeAccessible (Field field) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
|| Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
/**
* , Class,
* , Object.class.
*/
@SuppressWarnings("unchecked")
public static <T> Class<T> getClassGenricType (final Class clazz) {
return getClassGenricType(clazz, 0);
}
/**
* , Class.
* , Object.class.
*/
public static Class getClassGenricType (final Class clazz, final int index) {
Type genType = clazz.getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType");
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
+ params.length);
return Object.class;
}
if (!(params[index] instanceof Class)) {
logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
return Object.class;
}
return (Class) params[index];
}
public static Class<?> getUserClass (Object instance) {
if (instance == null) {
throw new RuntimeException("Instance must not be null");
}
Class clazz = instance.getClass();
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
Class<?> superClass = clazz.getSuperclass();
if (superClass != null && !Object.class.equals(superClass)) {
return superClass;
}
}
return clazz;
}
/**
* checked exceptionunchecked exception.
*/
public static RuntimeException convertReflectionExceptionToUnchecked (String msg, Exception e) {
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|| e instanceof NoSuchMethodException) {
return new IllegalArgumentException(msg, e);
} else if (e instanceof InvocationTargetException) {
return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException());
}
return new RuntimeException(msg, e);
}
}