[java]框架中為什么用到反射?


反射 注解的使用

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface GetMapping {
    String value();
}

public class MyTest {
    public static void main(String[] args) throws Exception {
        Class<A> aClass = A.class;
        for (Method method : aClass.getMethods()) {
            if (method.getAnnotation(GetMapping.class) != null) {

                //獲取參數類型
                for (Class<?> parameterType : method.getParameterTypes()) {
                    System.out.println(parameterType);
                }

                //參數名
                for (Parameter parameter : method.getParameters()) {
                    System.out.println(parameter.getName());
                }
                //獲取返回值類型
                System.out.println(method.getReturnType());
                //獲取注解value
                System.out.println(method.getAnnotation(GetMapping.class).value());
            }
        }

    }
}

class A {
    public A() {
    }

    @GetMapping("/index")
    public void show(String name, Integer age) {
        System.out.println("A.show");
    }
}

框架中用反射

關鍵點在於擴展: 反射會自動幫忙整理.

試想如果沒有反射怎么做? 先定義一個map. 添加若干controller. 每次添加一個controller 都得改一下路由map. 顯得麻煩.
前端訪問時,根據約好的controller path來訪問即可.

有沒有一種辦法, 讓我專注於我的controller. 路由之類的別來煩我. springmvc的做法是全局創建一個controller. 用反射調用方法

servlet生命周期的init. 當servlet創建時會被自動執行.

   HTTP Request    ┌─────────────────┐
──────────────────>│DispatcherServlet│
                   └─────────────────┘
                            │
               ┌────────────┼────────────┐
               ▼            ▼            ▼
         ┌───────────┐┌───────────┐┌───────────┐
         │Controller1││Controller2││Controller3│
         └───────────┘└───────────┘└───────────┘
               │            │            │
               └────────────┼────────────┘
                            ▼
   HTTP Response ┌────────────────────┐
<────────────────│render(ModelAndView)│
                 └────────────────────┘


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM