zoukankan      html  css  js  c++  java
  • 使用反射,调用有参数的方法

    1.创建Person类,写几个方法

    package seday18c;
    /**
     * @author xingsir
     * 创建一个Person类,写几个方法
     */
    public class Person {
    	public void eat() {
    		System.out.println("我在吃");
    	}
    	public void run() {
    		System.out.println("我在跑");
    	}
    	public void eat(String name) {
    		System.out.println("我是"+name+",我在吃");
    	}
    	public void eat(String name,int count) {
    		System.out.println("我是"+name+",我在吃"+count+"只牛蛙");
    	}
    
    }
    

      2.创建调用有参数的方法

    package seday18c;
    
    import java.lang.reflect.Method;
    
    /**
    * @author xingsir
    * 使用反射,调用有参数的方法
    */
    public class ReflectDemo4 {
    
    	public static void main(String[] args) throws Exception {
    		
    		Class cls= Class.forName("seday18c.Person");
    		//实例化
    		Object o =cls.newInstance();
    		//获取方法
    		Method m= cls.getMethod("eat", String.class);
    		m.invoke(o, "八戒");
    		
    		Method m2 = cls.getMethod(
    				"eat",String.class,int.class);
    		m2.invoke(o, "八戒",1);
    	}
    
    }
    

      

  • 相关阅读:
    【C#】工具类-FTP操作封装类FTPHelper
    网盘搜索网站
    在线服务
    Windows下安装NTP服务器
    vue 组件间的传值 + 路由守卫
    功能6 -- 选项卡数据缓存
    vue2.0/3.0
    vuex
    mySql笔记
    Typescript
  • 原文地址:https://www.cnblogs.com/xingsir/p/12667349.html
Copyright © 2011-2022 走看看