152、测试反射---获取对象方法并执行

ReflexDemo04.java

import java.lang.reflect.Method;

public class ReflexDemo04 {
    public static void main(String[] args) throws Exception {
        Class pC = Person.class;

        Person ps = new Person();

        //获取无参方法
        Method eat1 = pC.getMethod("eat");
        eat1.invoke(ps);

        //获取有参方法
        Method eat2 = pC.getMethod("eat", String.class);
        eat2.invoke(ps,"青菜");

        System.out.println("===================================");
        Method[] methods = pC.getMethods();
        for (Method method : methods) {
            System.out.println(method);
            System.out.println(method.getName());
        }
    }
}

输出:

我在吃东西!
我在吃:青菜
===================================
public java.lang.String cn.lwgk.Reflex.Person.toString()
toString
public java.lang.String cn.lwgk.Reflex.Person.getName()
getName
public void cn.lwgk.Reflex.Person.setName(java.lang.String)
setName
public int cn.lwgk.Reflex.Person.getBir()
getBir
public void cn.lwgk.Reflex.Person.setBir(int)
setBir
public void cn.lwgk.Reflex.Person.setSchool(java.lang.String)
setSchool
public java.lang.String cn.lwgk.Reflex.Person.getSchool()
getSchool
public void cn.lwgk.Reflex.Person.setAge(int)
setAge
public int cn.lwgk.Reflex.Person.getAge()
getAge
public void cn.lwgk.Reflex.Person.eat()
eat
public void cn.lwgk.Reflex.Person.eat(java.lang.String)
eat
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
wait
public final void java.lang.Object.wait() throws java.lang.InterruptedException
wait
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
wait
public boolean java.lang.Object.equals(java.lang.Object)
equals
public native int java.lang.Object.hashCode()
hashCode
public final native java.lang.Class java.lang.Object.getClass()
getClass
public final native void java.lang.Object.notify()
notify
public final native void java.lang.Object.notifyAll()
notifyAll

 

你可能感兴趣的:(01_JAVA)