• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
第二天半
博客园    首页    新随笔    联系   管理    订阅  订阅

反射认识_04_反射调用类方法Method

包1:

package ReflectionMethod;

public class ReflectionMethod {
	String str1="str1";
	
	public void outStr1(){
		System.out.println("输出第一个字符串:"+str1);
	}
	public void outStr2(String str2){
		System.out.println("输出第二个字符串:"+str2);
	}
	public void outStr3(String str3,String str4){
		System.out.println("输出第三个字符串:"+str3);
		System.out.println("输出第四个字符串:"+str4);
	}
}

  

包2:

package ReflectionMethod;

import java.lang.reflect.Method;

public class ReflectionAchieve {

	public static void main(String[] args) throws Exception {
		ReflectionMethod rp=new ReflectionMethod();
		useMethod(rp); 
	}
	
	public static void useMethod(Object obj) throws Exception{
		/*调用方法1,不带参数*/
		Method out1=obj.getClass().getMethod("outStr1");//通过对象获得类,通过类获得类方法
		out1.invoke(obj);//传入对象,并使用方法,如果是静态方法,可以传入null
		/*调用方法2,带1个参数*/
		Method out2=obj.getClass().getMethod("outStr2",String.class);//通过对象获得类,传入方法参数类型,通过类获得类方法
		out2.invoke(obj,"str2");//传入对象,传入变量,并使用方法
		/*调用方法3,带多个参数*/
		Method out3=obj.getClass().getMethod("outStr3",String.class,String.class);//通过对象获得类,传入多个参数类型,通过类获得类方法
		out3.invoke(obj,"str3","str4");//传入对象,传入多个变量,-使用方法
	}
}

  

posted @ 2014-12-06 22:13  第二天半  阅读(185)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3