📄 callmethoddemo.java
字号:
import java.lang.reflect.*;
public class CallMethodDemo
{
public static void main(String[] args)
{
//获取Class对象用来描述自定义类Employee
Class c = Employee.class;
//用于定义所调用方法中,所包含的参数形式
Class parameter_Type[] = new Class[3];
parameter_Type[0] = String.class;
parameter_Type[1] = Integer.TYPE;
parameter_Type[2] = String.class;
//用于定义运行时调用的方法的实际参数
Object value[] = new Object[3];
value[0] = new String("wangxyw");
value[1] = new Integer(24);
value[2] = new String("male");
try
{
//创建方法对象,该方法参数名为"setAll",参数形式为Class型数组parameter_Type定义的形式
Method m = c.getMethod("setAll",parameter_Type);
//运行时创建类对象
Object obj = null;
obj = c.newInstance();
Employee em = (Employee)obj;
//运行时调用类对象中的方法
Object r = m.invoke(em, value);
//显示调用方法后,类对象中的属性值
System.out.println(em.get_name());
System.out.println(em.get_age());
System.out.println(em.get_sex());
}
catch (SecurityException e1) {e1.printStackTrace();}
catch (NoSuchMethodException e1) {e1.printStackTrace();}
catch (InstantiationException e) {e.printStackTrace();}
catch (IllegalAccessException e) {e.printStackTrace();}
catch(InvocationTargetException e) {e.printStackTrace();}
}
}
class Employee //自定义类
{
private String name;
private int age;
private String sex;
public Employee() //无参数构造方法
{}
//含参数构造方法
public Employee(String name,int age,String sex)
{
this.name = name;
this.age = age;
this.sex = sex;
}
//获取自定义类属性值方法
public String get_name(){return name;}
public int get_age(){return age;}
public String get_sex(){return sex;}
//自定义类改变属性值方法
public void setAll(String name,int age,String sex)
{
this.name = name;
this.age = age;
this.sex = sex;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -