反射:
反射获取类的实体:
class Factory{
public static fruit getInstance(String ClassName){
fruit f=null;
try{
f=(fruit)Class.forName(ClassName).newInstance();
}catch (Exception e) {
e.printStackTrace();
}
return f;
}
}
class hello{
public static void main(String[] a){
fruit f=Factory.getInstance("Reflect.Apple");
if(f!=null){
f.eat();
}
}
反射调用属性的操作方法:
public class Person implements Serializable {
private String name;
private int age;
// get/set方法
}
public static void main(String[] args) {
Person person = new Person("luoxn28", 23);
Class clazz = person.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
String key = field.getName();
PropertyDescriptor descriptor = new PropertyDescriptor(key, clazz);
Method method = descriptor.getReadMethod();
Object value = method.invoke(person);
System.out.println(key + ":" + value);
}
}
反射获取具体实体的某一个字段值的快速方法(包括list):
field.get(object);
/**
* 检查bean中含有List的必要参数
*
* @param object
* @return
* @throws Exception
*/
public static String checkBeans(Object object) throws Exception {
Class cls = object.getClass();
StringBuilder stringBuilder = new StringBuilder();
for (; cls != Object.class; cls = cls.getSuperclass()) {//从本类一直遍历到父类
Field[] fieldes = cls.getDeclaredFields();
for (Field field : fieldes) {
field.setAccessible(true);
NotEmpty annotation = field.getAnnotation(NotEmpty.class);
IsJsonArray isJsonArray = field.getAnnotation(IsJsonArray.class);
Valid valid = field.getAnnotation(Valid.class);
if (annotation != null
&& StringUtils.isBlank((String) field.get(object))) {
stringBuilder.append(field.getName());
stringBuilder.append(";");
}
if (isJsonArray != null
&& !JsonUtils.isJsonArrayString((String) field.get(object))) {
stringBuilder.append(field.getName());
stringBuilder.append(";");
}
if (valid != null
&& !ArrayIsNotNull.isNull( (List
List
for(Object o : os){
checkBean(stringBuilder,o);
}
}else if(valid != null && ArrayIsNotNull.isNull( (List
stringBuilder.append(field.getName());
stringBuilder.append(";");
}
}
}
return stringBuilder.toString();
}
反射的一些使用特征,1,基于目标对象,方法对象操作 2,和常规的对象.方法相反(方法对象.对象)
method.invoke(TYZDSxPTAPI.instance();
public ApiResponse apiSend(FacadeSendRequest facadeSendRequest) throws Exception{
String methodName = urlEnum.getUrl();
//将packet中的json字符串转成接口参数map
log.info("解析api方法名为:[{}]",methodName);
String jsonStr = facadeSendRequest.getPacket();
Map
Method method = TYZDSxPTAPI.class.getMethod(methodName, Map.class);
if(method == null){
log.error("类TYZDSxPTAPI中未找到对应方法函数:[{}]",methodName);
}
String logStr = JSONObject.toJSONString(paramMap);
log.info("开始调用TYZDSxPTAPI.{}:参数:{}",methodName,logStr.length() > 10000 ? (logStr.substring(0, 10000) + "...") : logStr);
Map
if ("TYZDAdvceListQry".equals(methodName)) {//临时注释
Map
returnMap = DataUtil.dealResult(rspMap);
} else {
returnMap = (Map
}
log.info("结束调用TYZDSxPTAPI.{}:返回:{}",methodName,JSONObject.toJSONString(returnMap));
return afterSend(facadeSendRequest.getTradeCode(),JSONObject.toJSONString(returnMap));
}