生活随笔
收集整理的這篇文章主要介紹了
反射_Class对象功能_获取Method
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
* Method:方法對象
?? ?* 執行方法:
?? ??? ?* Object invoke(Object obj, Object... args) ?
?? ?* 獲取方法名稱:
?? ??? ?* String getName:獲取方法名
package cn.learn.domain;public class Person {public void eat(){System.out.println("eat...");}public void eat(String food){System.out.println("eat..."+food);}
}
package cn.learn.reflect;import cn.learn.domain.Person;import java.lang.reflect.Constructor;
import java.lang.reflect.Method;public class ReflectDemo4 {/**Class對象功能:* 獲取功能:1. 獲取成員變量們* Field[] getFields()* Field getField(String name)* Field[] getDeclaredFields()* Field getDeclaredField(String name)2. 獲取構造方法們* Constructor<?>[] getConstructors()* Constructor<T> getConstructor(類<?>... parameterTypes)* Constructor<T> getDeclaredConstructor(類<?>... parameterTypes)* Constructor<?>[] getDeclaredConstructors()3. 獲取成員方法們:* Method[] getMethods()* Method getMethod(String name, 類<?>... parameterTypes)* Method[] getDeclaredMethods()* Method getDeclaredMethod(String name, 類<?>... parameterTypes)4. 獲取類名* String getName()*/public static void main(String[] args) throws Exception {//0.獲取Person的Class對象Class personClass = Person.class;/*3. 獲取成員方法們:* Method[] getMethods()* Method getMethod(String name, 類<?>... parameterTypes)* Method[] getDeclaredMethods()* Method getDeclaredMethod(String name, 類<?>... parameterTypes)*///獲取指定名稱的方法Method eat_method = personClass.getMethod("eat");Person p = new Person();//執行方法eat_method.invoke(p);Method eat_method2 = personClass.getMethod("eat", String.class);//執行方法eat_method2.invoke(p,"飯");System.out.println("-----------------");//獲取所有public修飾的方法Method[] methods = personClass.getMethods();for (Method method : methods) {System.out.println(method);String name = method.getName();System.out.println(name);//method.setAccessible(true);}//獲取類名String className = personClass.getName();System.out.println(className);//cn.learn.domain.Person}}
?
總結
以上是生活随笔為你收集整理的反射_Class对象功能_获取Method的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。