java反射新的应用

利用java反射动态修改运行中对象的私有final变量,不管有没有get方法获取这个私有final变量。

spring aop 本质是cglib,动态代理

可以做很多事情

query.addCriteria(criteria);

            queryCount.addCriteria(criteria);

            Class<?> queryClassType = query.getClass();

            Class<?> queryCountClassType  = queryCount.getClass();

            try {

                Field field = queryClassType.getDeclaredField("criteria");

                field.setAccessible(true);

                Field fieldQueryCount = queryCountClassType.getDeclaredField("criteria");

                fieldQueryCount.setAccessible(true);

                

                try {

                    System.out.println(field.get(query));

                    Map<String, Criteria> mapCriteriaTemp = (Map<String, Criteria>) field.get(query);

                    Criteria criteriaTemp = mapCriteriaTemp.get(null);

                    mapCriteriaTemp.remove(null);

                    mapCriteriaTemp.put("temp", criteriaTemp);

                    field.set(query, mapCriteriaTemp);

                    System.out.println(field.get(query));

                    

                    System.out.println(fieldQueryCount.get(queryCount));

                    Map<String, Criteria> mapCountCriteriaTemp = (Map<String, Criteria>) fieldQueryCount.get(queryCount);

                    Criteria criteriaCountTemp = mapCountCriteriaTemp.get(null);

                    mapCountCriteriaTemp.remove(null);

                    mapCountCriteriaTemp.put("temp", criteriaCountTemp);

                    fieldQueryCount.set(queryCount, mapCountCriteriaTemp);

                    System.out.println(fieldQueryCount.get(queryCount));

                } catch (IllegalArgumentException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                } catch (IllegalAccessException e) {

                    // TODO Auto-generated catch block

                    e.printStackTrace();

                }

            } catch (NoSuchFieldException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (SecurityException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            

            query.addCriteria(criteriaOrderBy);

            

            queryCount.addCriteria(criteriaCount);
View Code

 

你可能感兴趣的:(java反射)