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

 

posted @ 2014-10-30 09:45  唾手可得的树  阅读(204)  评论(0编辑  收藏  举报