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?"); }}