首页 > 编程 > Java > 正文

java 反射method 相关

2019-11-08 01:22:29
字体:
来源:转载
供稿:网友
package test;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;public class TestMethodReflect { public static final String ID = "Id"; public static final String NAME = "Name"; public static final String DESCRipTION = "Description"; //方法名集合 public static final String[] ALL = { ID, NAME, DESCRIPTION }; //这是测试数据 public static final String[] MODELDATA = { "1", "Gavin", "this is model's test data" };  public static void main(String[] args) { try { //获得Model类 Class model = Class.forName("test.Model"); //获得Model类的实例 Object object = model.newInstance(); for (int i = 0; i <</SPAN> ALL.length; i++) { //获得Model类的set方法,参数为String类型 Method setMethod = model.getMethod("set" + ALL[i], String.class); //调用set方法 setMethod.invoke(object, MODELDATA[i]); //获得Model类的get方法,无参数 Method getMethod = model.getMethod("get" + ALL[i], null); //调用get方法,并输出数据 System.out.PRintln(getMethod.invoke(object, null)); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalArgumentException e) { //
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表