zoukankan      html  css  js  c++  java
  • 反射

    反射就是可以通过获取类的类类型,再通过类的类类型获取类的信息(比如方法),通过反射可以直接调用方法

    m.invoke(a1,10,20)

    m:是通过类类型获得类的方法

    a1:是类的对象

    10,20:方法所需要的参数

    使用反射有什么好处?我们可以通过方法的反射来操作,绕过编译,绕过编译操作就绕过了泛型。

     1 package com.imooc.reflect;
     2 
     3 import java.lang.reflect.Method;
     4 
     5 public class MethodDemo1 {
     6     public static void main(String[] args) {
     7        //要获取print(int ,int )方法  1.要获取一个方法就是获取类的信息,获取类的信息首先要获取类的类类型
     8         A a1 = new A();
     9         Class c = a1.getClass();
    10         /*
    11          * 2.获取方法 名称和参数列表来决定  
    12          * getMethod获取的是public的方法
    13          * getDelcaredMethod自己声明的方法
    14          */
    15         try {
    16             //Method m =  c.getMethod("print", new Class[]{int.class,int.class});
    17             Method m = c.getMethod("print", int.class,int.class);
    18             
    19             //方法的反射操作  
    20             //a1.print(10, 20);方法的反射操作是用m对象来进行方法调用 和a1.print调用的效果完全相同
    21             //方法如果没有返回值返回null,有返回值返回具体的返回值
    22             //Object o = m.invoke(a1,new Object[]{10,20});
    23             Object o = m.invoke(a1, 10,20);
    24             System.out.println("==================");
    25             //获取方法print(String,String)
    26              Method m1 = c.getMethod("print",String.class,String.class);
    27              //用方法进行反射操作
    28              //a1.print("hello", "WORLD");
    29              o = m1.invoke(a1, "hello","WORLD");
    30              System.out.println("===================");
    31            //  Method m2 = c.getMethod("print", new Class[]{});
    32                 Method m2 = c.getMethod("print");
    33                // m2.invoke(a1, new Object[]{});
    34                 m2.invoke(a1);
    35         } catch (Exception e) {
    36             // TODO Auto-generated catch block
    37             e.printStackTrace();
    38         } 
    39      
    40     }
    41 }
    42 class A{
    43     public void print(){
    44         System.out.println("helloworld");
    45     }
    46     public void print(int a,int b){
    47         System.out.println(a+b);
    48     }
    49     public void print(String a,String b){
    50         System.out.println(a.toUpperCase()+","+b.toLowerCase());
    51     }
    52 }
  • 相关阅读:
    IntelliJ IDEA 常用设置讲解
    Maven
    FileStram文件正由另一进程使用,该进程无法访问该文件,解决方法
    IIS 调用Microsoft.Office.Interop.Word.Documents.Open 返回为null
    .NET 中的 async/await 异步编程
    PHP表单验证内容是否为空
    PHP中的魔术变量
    PHP中的function函数详解
    PHP中的循环while、do...while、for、foreach四种循环。
    利用switch语句进行多选一判断。
  • 原文地址:https://www.cnblogs.com/songsongblue/p/10108716.html
Copyright © 2011-2022 走看看