zoukankan      html  css  js  c++  java
  • 反射

    package com.bestpay.test;

    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;

    /**
    * Created by Administrator on 2016/4/22.
    */
    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) throws Exception{
    try {
    //获得Model类
    Class model = Class.forName("test.Model");
    //获得Model类的实例
    Object object = model.newInstance();
    for (int i = 0; i < 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) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (InvocationTargetException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (InstantiationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

    }
    }

















    package com.bestpay.test;

    /**
    * Created by Administrator on 2016/4/22.
    */
    public class Model {
    private String id;
    private String name;
    private String description;

    public Model() {
    id = "id";
    name = "name";
    description = "description";
    }

    public String getId() {
    return id;
    }

    public void setId(String id) {
    this.id = id;
    }

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getDescription() {
    return description;
    }

    public void setDescription(String description) {
    this.description = description;
    }

    }
  • 相关阅读:
    1230 jquery
    1221 监听事件
    1218 dom表格元素操作
    1216 DOM
    Java中对小数的向下取整,向上取整
    Mysql中 在SQL语句里进行日期格式转换
    一些常用格式化。价格、日期等 持续更新
    List对象里面根据某一字段去重
    java 后端 初始化图片像素(1980 x 1080)大小
    swagger里面测试List数据格式
  • 原文地址:https://www.cnblogs.com/dinglulu/p/5429736.html
Copyright © 2011-2022 走看看