Java中通过注解+反射拿到对象的属性和方法

来源:互联网 发布:手机激光测距软件 编辑:程序博客网 时间:2024/06/08 17:58

1什么是反射?

java通常是先有类再有对象,有对象我就可以调用方法或者属性。反射其实是通过Class对象来调用类里面的方法

下面就是测试代码,里面有详细的注释

package com.shandain.demo;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//添加在属性上面@Target(ElementType.FIELD)//运行时可见@Retention(RetentionPolicy.RUNTIME)public @interface NoteId {}
import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target(ElementType.FIELD)@Retention(RetentionPolicy.RUNTIME)public @interface NoteName {}

 
package com.shandain.demo;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;//声明在方法上@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface NodeShow {}
 
package com.shandain.demo;public class Node {@NoteIdprivate int id;@NoteNameprivate String name;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}@NodeShowpublic void show(){System.out.println(name);}}

 
package com.shandain.demo;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.util.List;public class Texst {public static void main(String[] args) {Node node = new Node();node.setId(2);node.setName("哈哈");show(node);}public static void show(Node node) {Class c = Node.class;// 获取改类的所有属性Field[] fields = c.getDeclaredFields();for (Field field : fields) {int id = -1;Object name = "";// 在该属性上的注释if (field.getAnnotation(NoteId.class) != null) {// 设置这个时是可以访问私有权限的field.setAccessible(true);try {id = field.getInt(node);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(id);}if (field.getAnnotation(NoteName.class) != null) {field.setAccessible(true);try {name = field.get(node);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println((String) name);}}// 取出此类的方法Method[] methods = c.getDeclaredMethods();for (Method method : methods) {if (method.getAnnotation(NodeShow.class) != null) {method.setAccessible(true);// 增加访问权限级别String name = method.getName();//获取方法名try {//执行反射出来的方法,第一个参数的值是你要执行那个类,第二个参数是该方法中的参数object[]method.invoke(node, null);} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}}




1 0