加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java通过反射创建对象并调用方法

发布时间:2020-12-15 00:29:37 所属栏目:Java 来源:网络整理
导读:这篇文章主要介绍了java通过反射创建对象并调用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.用户类 package com.lf.entity;import com.lf.annotation.SetProperty;import com.lf.annotation.S

这篇文章主要介绍了java通过反射创建对象并调用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.用户类

package com.lf.entity;

import com.lf.annotation.SetProperty;
import com.lf.annotation.SetTable;

public class UserEntity {
  private String userName;
  private int userAge;

  private final int money = 10000;

  public String getUserName() {
    return userName;
  }
  public void setUserName(String userName) {
    this.userName = userName;
  }
  public int getUserAge() {
    return userAge;
  }
  public void setUserAge(int userAge) {
    this.userAge = userAge;
  }
  //借钱方法
  public int getMoney(){
    System.out.println("你借了 " + money + "元!");
    return money;
  }
  //还钱方法,单个参数
  public void repay(int money){
    System.out.println("你还了 " + money + "元!");
  }
  //还钱方法,多个参数
  public void repay(String userName,int money){
    System.out.println(userName+ " 还了 " + money + "元!");
  }
}

2.测试类

package com.lf.test;

import java.lang.reflect.Method;

import com.lf.entity.UserEntity;

public class Reflection {

  //反射调用方法获取返回值
  //第一种方法,获取对象,直接通过对象调用方法
  //第二种方法,通过方法名获取方法,执行方法
  public static void main(String[] args) throws Exception {
    Class<?> userClass = Class.forName("com.lf.entity.UserEntity");
    UserEntity userEntity = (UserEntity) userClass.newInstance();

    //第一种方法
    System.out.println("第一次借钱:");
    int money = userEntity.getMoney();
    System.out.println("实际拿到钱为: " + money);
    System.out.println("------------------------分割线------------------------");

    //第二种方法,(无参的示例:借钱)
    System.out.println("第二次借钱:");
    Method getMoney = userClass.getMethod("getMoney");//得到方法对象
    Object money2 = getMoney.invoke(userEntity);//调用借钱方法,得到返回值
    System.out.println("实际拿到钱为:" + money2);
    System.out.println("------------------------分割线------------------------");

    //第二种方法,(单个参数的示例:还钱)
    System.out.println("第一次还钱:");
    Method repay1 = userClass.getMethod("repay",int.class);//得到方法对象,有参的方法需要指定参数类型
    repay1.invoke(userEntity,3000);//执行还钱方法,有参传参
    System.out.println("------------------------分割线------------------------");

    //第二种方法,(单个参数的示例:还钱)
    System.out.println("第二次还钱:");
    Method repay2 = userClass.getMethod("repay",String.class,有参的方法需要指定参数类型
    repay2.invoke(userEntity,"小飞",5000);//执行还钱方法,有参传参

  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读