java 注解的作用_一个Java例子,解释清楚注解的作用

Table注解

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Target(ElementType.TYPE) // 可以应用于类的任何元素

@Retention(RetentionPolicy.RUNTIME) //:在运行时有效(即运行时保留)

public @interface Table {

String value();

}

Column注解

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 Column {

String value();

}

Person类

package com.raykeyzzz.annotation;

@Table("Person")

public class Person {

@Column("name")

private String name;

@Column("userName")

private String userName;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getUserName() {

return userName;

}

public void setUserName(String userName) {

this.userName = userName;

}

}

Main类

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;

public class Main {

public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {

Person p1 = new Person();

p1.setName("ai");

p1.setUserName("aiai");

String query = query(p1);

System.out.println(query);

}

public static String query(Person person) throws InvocationTargetException, IllegalAccessException {

StringBuilder sb = new StringBuilder();

// 通过反射获取对象

Class p = person.getClass();

// 判断class类是不是注解类

boolean exist = p.isAnnotationPresent(Table.class);

if (!exist) {

return null;

}

// 如果是强制转化为Table

Table table = (Table) p.getAnnotation(Table.class);

String tableName = table.value();

// 接下来就是拼接sql语句

sb.append("select * from ").append(tableName).append(" where 1=1");

Field[] fArray = p.getDeclaredFields();

for (Field field : fArray) {

boolean fExist = field.isAnnotationPresent(Column.class);

if (!fExist) {

return null;

}

Column column = field.getAnnotation(Column.class);

String columnName = column.value();

String fieldName = field.getName();

Object fieldValue = null;

//此处将生成getXXX方法,用于下面通过反射执行对应方法拿到里面的返回值

String getMethodName = "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);

try {

Method method = p.getMethod(getMethodName);

fieldValue = method.invoke(person);

} catch (NoSuchMethodException e) {

e.printStackTrace();

}

sb.append(" and ").append(columnName).append("=").append(fieldValue);

}

return sb.toString();

}

}

``

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值