package test.reflect; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class reflect { public static void main(String[] args) { try { // 實例化類
Object obj = Animal.class.newInstance(); String[] str = new String[]{}; /** * 獲取方法名稱 */ Method[] m=obj.getClass().getDeclaredMethods(); for (Method method : m) { Annotation[] an= method.getAnnotations(); for (Annotation annotation : an) { System.out.println("方法"+method.getName()+"的註解爲:"+annotation); } /** * 獲取每個方法中的參數 */ Class[] paramTypes= method.getParameterTypes(); for (Class class1 : paramTypes) { System.out.println("方法"+method.getName()+"的參數類型爲:"+class1.getName()); } System.out.println("方法名稱:"+method.getName()); } /** * 數組類型 的話類名前有[L */ Class paramClass = Class.forName("[Ljava.lang.String;"); String[] param = { "大象", "猴子", "人", "貓" }; /** * 反射獲取類中的方法 */ Method method = Animal.class.getMethod("setAnimal", paramClass); method.invoke(obj, (Object) param); method = Animal.class.getMethod("getAnimal"); String[] get= (String[]) method.invoke(obj); // 取值 for (int i = 0; i < get.length; i++) { System.out.println(get[i]); } System.out.println(); } catch (Exception e) { e.printStackTrace(); } } } class Animal { private String[] animal; public String[] getAnimal() { return animal; } @Deprecated public void setAnimal(String[] animal) { this.animal =animal; } private void eat(){ System.out.println("eat what?"); } }