java 字符串调用方法_利用java反射根据方法名称字符串调用方法

前提:

由对象获取一个.class对象:Class clazz = "hello world".getClass();        由对象的全包名获取一个.class对象:

Class clazz=Class.forName("java.lang.String");

学习的时候发现,int等基本数据类型不是对象,所以无法获得其class对象,使用过程中只能通过int.class获取

正文:

实体类package test;

public class Student {

private static Student student = new Student();

private String name;

private int age;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

public void method1(int param1,String param2) {

System.out.println(param1+param2);

}

}

测试类:package test;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class Test {

public static void main(String[] args) throws Exception {

Student stu = new Student();

stu.setAge(1);

stu.setName("lin");

//1.无参

Method method = stu.getClass().getMethod("getName");

String name = (String) method.invoke(stu);

//2.一参

Method method2 = stu.getClass().getMethod("setName",Class.forName("java.lang.String"));

method2.invoke(stu, "meng");

//3.多参

Method method3 = stu.getClass().getMethod("method1",int.class,Class.forName("java.lang.String"));//后两个参数获得的都是class对象

method3.invoke(stu,15, "zhang");

}

}

另附自写get和set函数://参数列表:

//1.目标所属对象 2.所用set函数名(全称不加()) 3.set值public void set(Info info,String fun,Object value) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException {

Method method = info.getClass().getMethod(fun,Class.forName(value.getClass().getCanonicalName()));

method.invoke(info, value);

}

public Object get(Info info,String fun) throws Exception {

Method method = info.getClass().getMethod(fun);

return method.invoke(info);

}使用过程中可自行将函数封装进模板类代替Info类

由于Object无法接收int等基本数据类型,故在实体类中时可将类型声明为Integerpublic Integer getSex() {

return sex;

}

public void setSex(Integer sex) {

this.sex = sex;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值