小的东西记载

内存模型:
http://note.youdao.com/noteshare?id=797cece32b9b5ba04123bb19c6ab6cbb&sub=599505BBDECC4365BF53B8C1B646921F

反射相关api东西:

Class<? extends Annotation> annType = annotation.annotationType();
            if (annType.getName().startsWith("java.")) {
                continue;
            }
package mainTest;

import test1.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        //获取类型
        Class clazz = Class.forName("test1.Student");

        //空构造
        Student student1 = (Student) clazz.newInstance();//反射方式获取空参构造方法
        System.out.println(student1);

        Constructor con1 = clazz.getConstructor();
        Student student2 = (Student) con1.newInstance();
        System.out.println(student2);

        //获取有参构造方法
        Constructor con2 = clazz.getConstructor(String.class, int.class, String.class);
        Student student3 = (Student) con2.newInstance("刘瑞祺", 10, "1001");
        System.out.println(student3);

        //反射获取私有成员变量并修改
        Constructor con3 = clazz.getConstructor(String.class, int.class, String.class);
        Student student4 = (Student) con3.newInstance("刘瑞祺", 10, "1001");
        Object obj1 = con3.newInstance("刘瑞祺", 10, "1001");
        Field name = clazz.getDeclaredField("id");
        name.setAccessible(true);
        name.set(student4,"1002");
        name.set(obj1, "1002");
        System.out.println(obj1);

        //反射获取公有成员变量并修改
        Constructor con4 = clazz.getConstructor(String.class);
        Student student5 = (Student) con4.newInstance("12.4");
        Field score = clazz.getField("score");
        score.set(student5, "99");
        System.out.println(student5);
        Constructor con5 = clazz.getConstructor(String.class, int.class, String.class, String.class);
        Student student6 = (Student) con5.newInstance("liuruiqi", 23, "1001", "23.5");
        Field score = clazz.getField("score");
        score.set(student6, "100");
        System.out.println(student6);

        //反射调用成员方法
        Constructor con1 = clazz.getConstructor();
        Student student7 = (Student) con1.newInstance();
        Method m = clazz.getMethod("eat");
        m.invoke(student7);
        Method m2 = clazz.getMethod("eat", String.class);
        m2.invoke(student7, "你");

        //调用静态方法
        Method m3 = clazz.getMethod("staticMethod");
        m3.invoke(null);

        //调用私有成员方法
        Constructor con3 = clazz.getConstructor();
        Object obj2 = con3.newInstance();
        Method m4 = clazz.getDeclaredMethod("privateMethod");
        m4.setAccessible(true);
        m4.invoke(obj2);

        //获取所有成员变量
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            System.out.println(fields[i]);
        }
        //获取所有方法
        Method[] methods = clazz.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            System.out.println(methods[i]);
        }

        //判断有没有注解
        boolean isExist = c.isAnnotationPresent(Decription.class);
        if (isExist){
            // 从类上获得自定义的注解
            Decription d = (Decription) c.getAnnotation(Decription.class);
            System.out.println(d.decription() + d.id());
        }
        // 得到该类及父类中的所有方法
        Method[] ms = c.getMethods();
        // 遍历所有方法
        for (Method m:ms){
            // 判断在方法上是否使用了自定的注解
            boolean isExistMothed = m.isAnnotationPresent(Decription.class);
            if (isExistMothed){
                // 从方法上获得自定义的注解
                Decription d = m.getAnnotation(Decription.class);
                System.out.println(d.decription());
            }
        }

        
    }
}




public static void main(String[] args) {   
        B b=new B();   
        out.println("通过Class.NewInstance()调用私有构造函数:");   
        b.newInstanceByClassNewInstance();   
        out.println("通过Constructor.newInstance()调用私有构造函数:");   
        b.newInstanceByConstructorNewInstance();   
    }   
    /*通过Class.NewInstance()创建新的类示例*/   
    private void newInstanceByClassNewInstance(){   
        try {/*当前包名为reflect,必须使用全路径*/   
            A a=(A)Class.forName("reflect.A").newInstance();   
        } catch (Exception e) {   
            out.println("通过Class.NewInstance()调用私有构造函数【失败】");   
        }  
    }  
      
    /*通过Constructor.newInstance()创建新的类示例*/   
    private void newInstanceByConstructorNewInstance(){   
        try {/*可以使用相对路径,同一个包中可以不用带包路径*/   
            Class c=Class.forName("A");   
            /*以下调用无参的、私有构造函数*/   
            Constructor c0=c.getDeclaredConstructor();   
            c0.setAccessible(true);   
            A a0=(A)c0.newInstance();   
            /*以下调用带参的、私有构造函数*/   
            Constructor c1=c.getDeclaredConstructor(new Class[]{int.class,int.class});   
            c1.setAccessible(true);   
            A a1=(A)c1.newInstance(new Object[]{5,6});   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   

				Map<String, Object> parameters = converterItemProperties.getParameters();
                PropertyDescriptor[] descriptors = ReflectUtils.getBeanSetters(type);
                for (PropertyDescriptor descriptor : descriptors) {
                    String name = descriptor.getName();
                    Object value = parameters.get(name);
                    Method method = descriptor.getWriteMethod();
                    if (method != null) {
                        try {
                            method.invoke(converter, value);
                        } catch (IllegalAccessException e) {
                            throw new ForestRuntimeException("An error occurred during setting the property " + type.getName() + "." + name, e);
                        } catch (InvocationTargetException e) {
                            throw new ForestRuntimeException("An error occurred during setting the property " + type.getName() + "." + name, e);
                        }
                    }
                }

D:\workspace-idea\home\github\coody-verification
总结:我有一个对象,那么我就能拿到这个对象的一切,最后再遍历的时候,我可以拿到它的注解,然后去到注解里面的值,进行判断!

流式克隆:

cn.hutool.core.util;
ObjectUtil.cloneByStream(ruleExecJSONObject);

遍历map以后都要用这种方式啊,其他的都过时了啊:

aMap.forEach( (k,v)->{System.out.println(k+" "+v);} );

注解没有set方法,如何动态的设置属性值

/**
	 * 设置注解字段值
	 * 
	 * @throws SecurityException
	 * @throws NoSuchFieldException
	 */
	public static void setAnnotationValue(Annotation annotation, String propertyName, Object value)
			throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
		InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
		Field declaredField = invocationHandler.getClass().getDeclaredField("memberValues");
		declaredField.setAccessible(true);
		Map<String, Object> memberValues = (Map<String, Object>) declaredField.get(invocationHandler);
		Object oldValue = memberValues.get(propertyName);
		if (oldValue != null) {
			value = PropertUtil.parseValue(value, oldValue.getClass());
		}
		memberValues.put(propertyName, value);
	}

获取类的父类的泛型:

//获取
Type genType = clazz.getGenericSuperclass();
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

//手动创建
Type type1 = new ParameterizedTypeImpl(HashMap.class, new Type[]{String.class, new ParameterizedTypeImpl(List.class, new Type[]{CharSequence.class}, null)}, null);
Assert.assertEquals(type, type1);

利用requestMappingHandlerMapping 和过滤器,能够实现抓取当前请求的方法上的和类的所有东西!包括注解啊!这岂不是挺好的!

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Autowired
    @Qualifier("executorService")
    private ExecutorService executorService;

public void saveLog(HttpServletRequest request, HttpServletResponse response) throws Exception {
        PatternsRequestCondition prevCondition = null;
        HandlerMethod handlerMethod = null;
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = requestMappingHandlerMapping.getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> methodEntry : handlerMethods.entrySet()) {
            RequestMappingInfo key = methodEntry.getKey();
            HandlerMethod value = methodEntry.getValue();
            PatternsRequestCondition patternsCondition = key.getPatternsCondition();
            PatternsRequestCondition matchingCondition = patternsCondition.getMatchingCondition(request);
            if (matchingCondition == null) {
                continue;
            }
            if (prevCondition == null) {
                prevCondition = matchingCondition;
                handlerMethod = value;
                continue;
            }
            //prevCondition优先级高
            if (prevCondition.compareTo(matchingCondition, request) == 1) {
                prevCondition = matchingCondition;
                handlerMethod = value;
            }
        }
        if (handlerMethod == null) {
            return;
        }
        saveLog(request, response, handlerMethod);
    }
    
	private void saveLog(
            HttpServletRequest request,
            HttpServletResponse response,
            HandlerMethod handlerMethod
    ) {
        //请求参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        String parameter = JSONObject.toJSONString(parameterMap);
        //请求路径
        String servletPath = request.getServletPath();
        Method method = handlerMethod.getMethod();
        //方法名称
        String methodName = method.getName();
        //类名称
        Class<?> beanType = handlerMethod.getBeanType();
        Auth classAuth = beanType.getDeclaredAnnotation(Auth.class);
        if (classAuth == null) {
            return;
        }
        String name = classAuth.name();
        String currentUser = ssoUserService.currentUser();
        executorService.execute(() -> {
            //功能名称
            String functionName = null;
            Auth auth = method.getDeclaredAnnotation(Auth.class);
            if (auth == null) {
                return;
            }
            functionName = name + ":" + auth.name();
            OperaLog operaLog = new OperaLog();
            operaLog.setCreateDate(new Date());
            operaLog.setModifyDate(operaLog.getCreateDate());
            operaLog.setParameter(servletPath);
            operaLog.setContent(parameter);
            operaLog.setOperation(functionName);
            //当前操作人
            operaLog.setOperator(currentUser);
            operaLog.setIp(getRealIp(request));
            operaLogDao.save(operaLog);
        });
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值