zoukankan      html  css  js  c++  java
  • java 自定annotation

    ##自定义的注解有四个注意的内容:

    * Target

    @Target(ElementType.TYPE) // 注解可以使用的位置
    * Retention

    @Retention(RetentionPolicy.RUNTIME)// 生命周期

    * Documented

    @Documented
    // 其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。

    * Inherited

    @Inherited// 可以被子类继承

    示例代码:

    Table.java

    @Target(ElementType.TYPE)
    // 注解可以使用的位置
    @Retention(RetentionPolicy.RUNTIME)
    // 生命周期
    @Documented
    // 其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。
    @Inherited
    // 可以被子类继承
    public @interface Table {
    	String value();
    
    }
    

     Column.java

    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Column {
    	String value();
    
    }
    

      实体类

      person.java

      

    @Table("person")
    public class Person {
    
    	@Column("id")
    	private int id;
    	
    	@Column("name")
    	private String name;
    	
    	@Column("age")
    	private int age;
    	
    	@Column("email")
    	private String email;
        
            //get/set...
    }
    

      测试类
      

    public static void main(String[] args) {
    		query(new Person());
    	}
    
    	public static String query(Object o) {
    		boolean b = o.getClass().isAnnotationPresent(Table.class);
    		if (!b) {
    			return null;
    		}
    
    		Table table = o.getClass().getAnnotation(Table.class);
    		String tableName = table.value();
    		System.out.println("tableName>>" + tableName);// 获取table表名
    
    		Field[] fields = o.getClass().getDeclaredFields();
    		for (Field f : fields) {
    			boolean feildIsAnnotationed = f.isAnnotationPresent(Column.class);
    			if (!feildIsAnnotationed) {
    				continue;
    			}
    			Column c = f.getAnnotation(Column.class);
    			System.out.println("列注解的值:" + c.value());// 获取注解的列名
    
    			String fieldName = f.getName();
    			System.out.println("列名:" + fieldName);
    			// 通过反射获取列的值
    			String getMethod = "get" + fieldName.substring(0, 1).toUpperCase()
    					+ fieldName.substring(1);
    			System.out.println("方法名:" + getMethod);
    			try {
    				Method method = o.getClass().getMethod(getMethod);
    				System.out.println("方法的返回值》》》" + method.invoke(o));
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
    		return null;
    	}
    

      

      

     

  • 相关阅读:
    HTML5文件上传前本地预览
    sql(2) DISTINCT
    sql (1)
    delphi 第4课
    delphi 第3课
    Delphi 第2课
    delphi 用户可以点击格式修改进行模板修改
    delphi 流程单打印
    Delphi 第一课
    【BZOJ4530】[Bjoi2014]大融合 LCT维护子树信息
  • 原文地址:https://www.cnblogs.com/fengyexjtu/p/5122958.html
Copyright © 2011-2022 走看看