您的位置:首页 > 其它

反射机制调用普通成员方法

2017-05-12 21:17 381 查看
一个类中的普通成员函数必须要在有实例的情况下才能调用,而产生实例的方法有三种,分别是new、clone()、反射。

先看一下下面这个类:

package com.andy.entity;

public class Cat {

private int age;//定义猫的年龄
private double weight;//定义猫的体重

public Cat(int age,double weight)
{
this.age=age;
this.weight=weight;
}

public Cat() {
System.out.println("-----这是无参构造函数-----------");
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public double getWeight() {
return weight;
}

public void setWeight(double weight) {
this.weight = weight;
}

@Override
public String toString() {
return "猫的年龄是"+age+"  体重是"+weight;
}

}


该类有无参构造函数(当程序中存在有参构造函数时,必须要明确给出无参构造函数,否则程序中就不存在无参构造函数),那么在进行实例化时就可以通过Class类提供的newInstance方法进行。

在Class类中提供一下关于类中Method 的操作:

一、
public Method[] getMethods()
该方法用于获取所有的成员方法

二、
public Method getMethod(String name,   Class<?>... parameterTypes)
根据参数用来调用指定的成员方法,其中name是方法名称,后面是数据类型参数。

注意:以上两个方法的返回类型是Method,该类中有一个用来执行函数的方法:`public Object invoke(Object obj, Object… args) 参数obj是执行体,即调用方法的实例,后面是方法所需要的参数的数据类型。

比如为了调用上面类中的setAge()、getAge()、setWeight()、getWeight()方法,用反射实现如下:

package com.andy.temp;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class Temp {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
String fildName1="age";
String fildName2="weight";
Class<?>class1=Class.forName("com.andy.entity.Cat");
try {
Constructor<?> constructor=class1.getConstructor(int.class,double.class);
Object cat=constructor.newInstance(2,2.6);//相当于正常情况下的new,会调用构造函数
System.out.println(class1);//输出“class com.andy.temp.Cat”
System.out.println(cat);//调用toString方法
Method setMet1=class1.getMethod("set"+initcap(fildName1), int.class);
Method getMet1=class1.getMethod("get"+initcap(fildName1));

Method setMet2=class1.getMethod("set"+initcap(fildName2), double.class);
Method getMet2=class1.getMethod("get"+initcap(fildName2));

setMet1.invoke(cat, 3);
System.out.println(getMet1.invoke(cat));

setMet2.invoke(cat, 2.3);
System.out.println(getMet2.invoke(cat));
System.out.println(cat);//调用toString方法

} catch (Exception e) {

e.printStackTrace();
}

}
public static String initcap(String str) {
return str.substring(0,1).toUpperCase()+str.substring(1).toLowerCase();
}
}


`

输出结果如下:

class com.andy.entity.Cat

猫的年龄是2 体重是2.6

3

2.3

猫的年龄是3 体重是2.3
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  反射-成员方法