本文主要内容:
(1)如何操作私有、公有及父类的方法
(2)如何操作构造方法
1.如何操作类中的方法
(1)Method m = class.getMethod();//class中获取类方法
(2)Method的常用方法
Method m = c.getMethod("eat",String.class);
int modifier = m.getModifiers();//获取方法修饰符
Class mrt = m.getReturnType();//获取返回值类型
String mn = m.getName();//获取名字
Class[] mpts = m.getParameterTypes();//获取参数列表
Class[] mets = m.getExceptionTypes();//获取方法抛出异常类型
(3)如何操作方法
Object result=invoke(对象,执行方法传递的所有参数…)
public class Person {
public void eat(){
System.out.println("我是人的eat方法");
}
public String eat(String s){
System.out.println("我是人带参的eat方法");
return s;
}
}
public class TestMethod {
public static void main(String[] args) {
//获取Person对应的类
Class c = Person.class;
//方法可以重名
//需要方法名,及方法参数
try {
Method m = c.getMethod("eat",String.class);
Person p = (Person) c.newInstance();
String result = (String) m.invoke(p,"测试参数");
System.out.println(result);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
(4)getMethod(“方法名”,“参数类型”)方法可以获取公有自己与父类的方法
public class Animal {
public void sleep(){
System.out.println("动物的睡觉方法");
}
}
public class Person {
public void eat(){
System.out.println("我是人的eat方法");
}
public String eat(String s){
System.out.println("我是人带参的eat方法");
return s;
}
}
public class TestMethod {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
//获取Person对应的类
Class c = Person.class;
//方法可以重名
//需要方法名,及方法参数
Method m = c.getMethod("eat", String.class);
Person p = (Person) c.newInstance();
Method m1 = c.getMethod("sleep");
m1.invoke(p);
}
}
(5)getDeclaredMethod(“方法名”,“参数类型”)方法可以自己类的公有、私有方法
public class Person extends Animal{
private void eat(){
System.out.println("我是人的eat方法,私有的");
}
public String eat(String s){
System.out.println("我是人带参的eat方法");
return s;
}
}
public class TestMethod {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
//获取Person对应的类
Class c = Person.class;
//方法可以重名
//需要方法名,及方法参数
Method m = c.getMethod("eat", String.class);
Person p = (Person) c.newInstance();
Method m1 = c.getDeclaredMethod("eat");
System.out.println(m1.getName());
m1.setAccessible(true);
m1.invoke(p);
}
}
//eat
//我是人的eat方法,私有的
(6)如何操作类中的构造方法
Constructor con = clazz.getConstructor(带参数类型);//返回构造方法
Person p = (Person)con.newInstance(执行构造方法的类型参数);//通过构造方法创建对象
(7)Constructor类中的常用方法
con.getModifiers();con.getName();
con.getParameterTypes();con.getExceptionTypes();
con.setAcesssable(true);