首页 > 其他分享 >反射获取注解,框架的基础

反射获取注解,框架的基础

时间:2024-02-28 16:00:20浏览次数:18  
标签:反射 account String 框架 public 注解 password type id

 

 

 

 

package aaa;


import java.lang.annotation.*;
import java.lang.reflect.Field;

public class test{
    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> u1 = Class.forName("aaa.User");
        //获取类的注解
        Annotation[] annotations = u1.getAnnotations();
        for(Annotation annotation:annotations){
            System.out.println(annotation);//@aaa.TableName("user")
        }
        //获得注解的value
        TableName tableName = u1.getAnnotation(TableName.class);
        String value = tableName.value();
        System.out.println(value);//user

        //获得类属性上的注解
        Field[] declaredFields = u1.getDeclaredFields();
        for(Field field:declaredFields){
            TableField annotation = field.getAnnotation(TableField.class);
            System.out.println(annotation+":"+annotation.columnName()+"--"+annotation.type());
            /*
              @aaa.TableField(columnName="id", type="int"):id--int
         @aaa.TableField(columnName="account", type="varchar"):account--varchar
        @aaa.TableField(columnName="password", type="varchar"):password--varchar
        */
        }
    }
}


@TableName("user")
class User{

    @TableField(columnName = "id", type = "int")
    private Long id;

    @TableField(columnName = "account", type = "varchar")
    private String account;

    @TableField(columnName = "password", type = "varchar")
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", account='" + account + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

//类名注解
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableName{
    String value();
}
//属性注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface TableField{
    String columnName();
    String type();
}

结合 ORM 框架时,一般会使用注解来标识实体类与数据库表之间的映射关系

package aaa;

import java.lang.annotation.*;
import java.lang.reflect.Field;

// 模拟 ORM 框架中的实体类
@Entity(tableName = "user_table")
class User {
    @Id
    @Column(name = "id", type = "bigint")
    private Long id;

    @Column(name = "account", type = "varchar(50)")
    private String account;

    @Column(name = "password", type = "varchar(50)")
    private String password;

    // 省略 getter 和 setter 方法

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", account='" + account + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

// 注解:实体类
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Entity {
    String tableName();
}

// 注解:主键
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Id {
}

// 注解:字段
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface Column {
    String name();
    String type();
}

// 测试类
public class Test {
    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> userClass = Class.forName("aaa.User");

        // 获取实体类的注解
        Entity entityAnnotation = userClass.getAnnotation(Entity.class);
        String tableName = entityAnnotation.tableName();
        System.out.println("Table Name: " + tableName);

        // 获取实体类的所有字段
        Field[] fields = userClass.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Column.class)) {
                Column columnAnnotation = field.getAnnotation(Column.class);
                String columnName = columnAnnotation.name();
                String columnType = columnAnnotation.type();
                System.out.println("Column: " + columnName + ", Type: " + columnType);
            } else if (field.isAnnotationPresent(Id.class)) {
                System.out.println("Primary Key: " + field.getName());
            }
        }
    }
}

输出

Table Name: user_table
Column: id, Type: bigint
Column: account, Type: varchar(50)
Column: password, Type: varchar(50)

标签:反射,account,String,框架,public,注解,password,type,id
From: https://www.cnblogs.com/laojiahuo/p/18040703

相关文章

  • 【Spring Framework】IoC容器、依赖注入 + 基于XML && 基于注解 && 基于Java Config配
    概念IoC,InversionofControl,控制反转:将对象的控制权交由第三方统一管理DI,DependencyInjection:依赖注入,使用反射技术,是一种IoC的实现SpringIoC容器:用于统一创建与管理对象依赖XML管理对象(bean):applicationContext.xmlSpring框架使用流程-基于XML配置IoC容器1.导入spring......
  • Mybatis系列之(三)注解开发步骤
    注解开发步骤1.项目结构新建项目,创建与XML开发完全相同的项目结构删除resources/com文件夹2.全局配置文件修改SqlMapConfig.xml文件的mapper配置部分<!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件--><mappers><!--resource......
  • SpringMVC系列之(三)常用注解
    常用注解1.RequestMappingRequestMapping可以放在类上和方法上,放在类上表示一级目录,或表示某一个具体的模块属性path和value属性的作用相同method决定方法的请求方式params:请求必须包含的参数headers:请求必须包含的请求头以上的属性出现多个,需要同时满足2.RequestPa......
  • 手写web框架
    重新认识HTTPhttp请求报文包含三个部分(请求行+请求头+请求体)请求行请求行包含三个内容:method+request-URI+http-version--例如GET/icwork/?Search=productHTTP/1.1请求方法请求方法作用get通过请求URI获得资源post用于添加新的资源,用于......
  • 框架和MVC架构
    网络框架及MVC架构网络框架所谓网络框架是指这样的一组Python包,它能够使开发者专注于网站应用业务逻辑的开发,而无须处理网络应用底层的协议、线程、进程等方面。这样能大大提高开发者的工作效率,同时提高网络应用程序的质量。在目前Python语言的几十个开发框架中,几乎所有的全栈......
  • 1-Django框架简介以及基本操作
    安装注意:安装的磁盘目录,以及后续通过Django创建目录的时候,不要出现中文,否则会出现预料之外的错误建议:禁止套娃,即不要在A项目中创建B项目#如果不指定版本号,默认最新版pipinstalldjango#如果要指定版本,使用==版本号pipinstalldjango==3.2.12查看是否安装成功可......
  • Spring系列之(五)Spring基于注解的IOC
    Spring基于注解的IOC1.构建注解环境在beans.xml中加入context名称空间和约束<?xmlversion="1.0"encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance&......
  • C# 简单反射加载 DLL 实例
    //反射判断是否位某个类型publicboolIsSubclassOf(thisTypetype,TypebaseType){//如果type不是null并且baseType是一个类(非接口)if(type!=null&&baseType.IsClass){returntype.IsSubclassOf(baseType);}//或者如果baseType是......
  • 纯手撸web框架
    纯手撸web框架(1)纯手撸#encoding:utf8#author:heart#blog_url:https://www.cnblogs.com/ssrheart/#time:2024/2/26importsocketserver=socket.socket()server.bind(('127.0.0.1',8080))server.listen(5)whileTrue:conn,addr=server.a......
  • Qt 常见数据结构详解:从基本框架到实际应用
    在Qt框架中,数据结构的选择对于提高代码效率和性能至关重要。正确地使用数据结构可以显著提高应用程序的效率和响应速度。下面我们将详细介绍Qt中常见的几种数据结构,包括QString、QList、QVector、QMap、QHash、QSet和QPair。1.QStringQString是Qt中用于处理字符串的类。......