• 反射机制调用无参和有参方法以及调用私有方法


    package reflect;
    
    public class Person {
    	
    	public void sayHello() {
    		System.out.println("HelloJava");
    	}
    	public void sayName() {
    		System.out.println("大家好");
    	}
    	public void sayAge(int age) {
    		System.out.println("我的年龄是:"+age+"岁了...");
    	}
    	public void say(String name,int age) {
    		System.out.println("我叫"+name+",我今年"+age+"岁了。");
    	}
    	private void domose() {
    		System.out.println("我是Preson类的私有方法...");
    		
    	}
    }
    

      

      调用person类中无参方法

    package reflect;
    
    import java.lang.reflect.Method;
    /**
     * 通过反射机制调用某个类的某个方法
     */
    
    public class ReflectDemo1 {
    	public static void main(String[] args) throws Exception  {
    		
    		Class cls = Class.forName("reflect.Person");
    		//接收的是一个Person的实例
    		Object o =cls.newInstance();
    		/*
    		 * 通过该Class实例可以获取其表示的类的相关方法
    		 * 获取Person的sayHello方法
    		 * 
    		 */
    		Method method =cls.getDeclaredMethod("sayHello", null);
    		method.invoke(o, null);
    	}
    
    }
    

      调用person类中有参方法

    package reflect;
    
    import java.lang.reflect.Method;
    
    /**反射调用有参方法
    * 
    */
    public class ReflectDemo3 {
    public static void main(String[] args) throws Exception {
    Class cls = Class.forName("reflect.Person");
    Object o =cls.newInstance();
    Method method=cls.getDeclaredMethod("sayAge",new Class[] {int.class});
    
    method.invoke(o, new Object[] {20});
    
    Method method1=cls.getDeclaredMethod("say",new Class[] {String.class,int.class});
    method1.invoke(o,new Object[] {"zhangsan",18});
    }
    
    }
    

      

    调用Person类中的私有方法

    package reflect;
    
    import java.lang.reflect.Method;
    
    //反射机制调用私有方法
    public class ReflectDemo4 {
    	public static void main(String[] args) throws Exception  {
    		Class cls = Class.forName("reflect.Person");
    		Object o =cls.newInstance();
    		Method method=cls.getDeclaredMethod("domose",null);
    		//强制要求访问该方法  setAccessible(true);
    		method.setAccessible(true);
    		method.invoke(o, null);
    		
    	}
    
    }
    

      

      

  • 相关阅读:
    力扣 227 :基本计算器(II)
    力扣 224 :基本计算器(I)
    力扣 888:公平的糖果棒交换(哈希表法)
    力扣 1047 :删除字符串中的所有相邻重复项
    力扣 1423 :可获得的最大点数
    vue+spreadjs+后台Java实现与服务端交互的导入导出
    webpack 中 require.context() 多个模块的加载
    dwd_fact_coupon_use
    dwd_fact_cart_info
    dwd_fact_order_detail
  • 原文地址:https://www.cnblogs.com/xyk1987/p/8350528.html
Copyright © 2020-2023  润新知