php自定义注解,自定义注解的使用

使用自定义注解和反射实现参数检查

一、首先定义一个参数检查的注解@RequestParam

package com.daily.java.AnotationAndReflect;

import java.lang.annotation.Documented;

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)

@Documented

public @interface RequestParam {

/**

* 参数名称

*

* @return

*/

String paramName() default "";

/**

* 是否可为空

* - 返回true时,如果此参数为空,则会在调用前抛出异常

*

* @return

*/

boolean notNull() default false;

/**

* 是否可为空或空字符串或空集合

* - 返回true时,如果此参数为空,则会在调用前抛出异常

*

* @return

*/

boolean notEmpty() default false;

}

二、定义一个参数检查的接口

package com.daily.java.AnotationAndReflect;

/**

* 需要参数检查的POJO必须实现此接口

*/

public interface Request {

}

三、工具类的实现

package com.daily.java.AnotationAndReflect;

import java.lang.reflect.Field;

import java.util.Collection;

import java.util.HashSet;

import java.util.Map;

import java.util.Set;

import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;

/**

* 请求工具类

* (1). 检查参数非空

* (2). 从request中提取参数

*/

public class RequestUtils {

private static final Logger log = LoggerFactory.getLogger(RequestUtils.class);

/**

* 请求的全部成员变量Map

* -- key : request.getClass().getName();

* -- value: request.getClass().getFields();

*/

private static final Map> All_FIELDS_MAP =new ConcurrentHashMap<>();

private static final Map> NOT_NULL_FIELDS_MAP = new ConcurrentHashMap<>();

private static final Set getAllFields(Object request) {

return getFields(request, All_FIELDS_MAP);

}

private static final Set getNotNullFields(Object request) {

return getFields(request, NOT_NULL_FIELDS_MAP);

}

private static final Set getFields(Object userCenterRequest, Map> cacheMap) {

String name = userCenterRequest.getClass().getName();

Set fields = cacheMap.get(name);

if (fields == null) {

initRequestFields(userCenterRequest);

fields = cacheMap.get(name);

}

return fields;

}

private static final void initClassFields(Class clazz, Set allFields, Set notNullFields) {

Field[] declaredFields = clazz.getDeclaredFields();

for (Field field : declaredFields) {

RequestParam annotation = field.getAnnotation(RequestParam.class);

if (annotation != null) {

field.setAccessible(true);

allFields.add(field);

if (annotation.notNull() || annotation.notEmpty()) {

notNullFields.add(field);

}

}

}

Class superclass = clazz.getSuperclass();

if (superclass != null && !superclass.isInterface()) {

initClassFields(superclass, allFields, notNullFields);

}

}

private static final void initRequestFields(Object request) {

String name = request.getClass().getName();

synchronized (name + "requestUtils") {

Set allFields = All_FIELDS_MAP.get(name);

if (allFields == null) {

Set notNullFields = new HashSet<>();

allFields = new HashSet<>();

initClassFields(request.getClass(), allFields, notNullFields);

NOT_NULL_FIELDS_MAP.put(name, notNullFields);

All_FIELDS_MAP.put(name, allFields);

}

}

}

/**

* 从request中提取调用参数(过滤为空的参数)

*

* @param request 请求

* @return

*/

public static final Map getRequestParams(Request request) {

return getRequestParams(request, true);

}

/**

* 从request中提取调用参数

*

* @param request 请求

* @param filterNullParam 是否过滤非空参数

* @return

*/

public static final Map getRequestParams(Object request, boolean filterNullParam) {

Set allFields = getAllFields(request);

Map requestParamMap = new ConcurrentHashMap<>();

try {

for (Field field : allFields) {

RequestParam annotation = field.getAnnotation(RequestParam.class);

if (annotation != null) {

Object objectValue = field.get(request);

if (objectValue == null && filterNullParam) {

continue;

}

String value=objectValue==null?"":objectValue.toString();

String paramName = annotation.paramName();

if (StringUtils.isEmpty(paramName)) {

paramName = field.getName();

}

requestParamMap.put(paramName, value);

} else {

Object value = field.get(request);

if (value == null && filterNullParam) {

continue;

}

Map requestParams = getRequestParams(value, filterNullParam);

if (requestParams != null && !requestParams.isEmpty()) {

requestParamMap.putAll(requestParams);

}

}

}

} catch (IllegalAccessException e) {

e.printStackTrace();

}

return requestParamMap;

}

/**

* 对request中的参数进行非空校验

*

* @param request

*/

public static final void checkRequestParams(Object request) {

Set notEmptyFields = getNotNullFields(request);

try {

for (Field field : notEmptyFields) {

Object value = field.get(request);

RequestParam annotation = field.getAnnotation(RequestParam.class);

if (annotation != null) {

if (annotation.notNull() && value == null) {

throw new IllegalArgumentException("Parameter " + field.getName() + " expects not to be null : " + request);

}

if (annotation.notEmpty()) {

// -- 2.1. 校验非空

if (value == null) {

throw new IllegalArgumentException("Parameter " + field.getName() + " expects not to be null : " + request);

}

// -- 2.2. 判断String类型的属性非空

if (value instanceof String && StringUtils.isEmpty((String) value)) {

throw new IllegalArgumentException("Parameter " + field.getName() + " expects not to be empty : " + request);

}

// -- 2.3. 判断集合类型的属性非空

if (value instanceof Collection && ((Collection) value).isEmpty()) {

throw new IllegalArgumentException("Parameter " + field.getName() + " expects not to be empty : " + request);

}

// -- 2.4. 判断Map类型的属性非空

if (value instanceof Map && ((Map) value).isEmpty()) {

throw new IllegalArgumentException("Parameter " + field.getName() + " expects not to be empty : " + request);

}

// -- 2.5. 判断数组类型的属性非空

if (field.getType().isArray() && JSON.toJSONString(value).equals("[]")) {

throw new IllegalArgumentException("Parameter " + field.getName() + " expects not to be empty : " + request);

}

}

}

}

} catch (IllegalAccessException e) {

log.error("checkRequestParams exception", e);

}

}

}

四、定义一个用于测试的POJO

/**

* 参数检查测试POJO

*/

public class Student implements Request {

@RequestParam(notEmpty = true)

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

五、测试

/**

* 使用自定义注解和反射实现参数检查

*/

public class AnotationAndReflectTest {

@Test

public void testRequestCheck() {

Student student = new Student();

student.setName("张三");

RequestUtils.checkRequestParams(student);

student.setName(null);

RequestUtils.checkRequestParams(student);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Hyperf 是基于 Swoole 4.5+ 实现的高性能、高灵活性的 PHP 协程框架,内置协程服务器及大量常用的组件,性能较传统基于 PHP-FPM 的框架有质的提升,提供超高性能的同时,也保持着极其灵活的可扩展性,标准组件均基于 PSR 标准 实现,基于强大的依赖注入设计,保证了绝大部分组件或类都是可替换 与可复用的。 框架组件库除了常见的协程版的 MySQL 客户端、Redis 客户端,还为您准备了协程版的 Eloquent ORM、WebSocket 服务端及客户端、JSON RPC 服务端及客户端、GRPC 服务端及客户端、Zipkin/Jaeger (OpenTracing) 客户端、Guzzle HTTP 客户端、Elasticsearch 客户端、Consul 客户端、ETCD 客户端、AMQP 组件、NSQ 组件、Nats 组件、Apollo 配置中心、阿里云 ACM 应用配置管理、ETCD 配置中心、基于令牌桶算法的限流器、通用连接池、熔断器、Swagger 文档生成、Swoole Tracker、视图引擎、Snowflake 全局 ID 生成器 等组件,省去了自己实现对应协程版本的麻烦。 Hyperf 还提供了基于 PSR-11 的依赖注入容器、注解、AOP 面向切面编程、基于 PSR-15 的中间件、自定义进程、基于 PSR-14 的事件管理器、Redis/RabbitMQ/NSQ/Nats 消息队列、自动模型缓存、基于 PSR-16 的缓存、Crontab 秒级定时任务、Translation 国际化、Validation 验证器等非常便捷的功能,满足丰富的技术场景和业务场景,开箱即用。 框架初衷: 尽管现在基于 PHP 语言开发的框架处于一个百家争鸣的时代,但仍旧未能看到一个优雅的设计与超高性能的共存的完美框架,亦没有看到一个真正为 PHP 微服务铺路的框架,此为 Hyperf 及其团队成员的初衷,我们将持续投入并为此付出努力,也欢迎你加入我们参与开源建设。 设计理念: Hyperspeed + Flexibility = Hyperf,从名字上我们就将超高速和灵活性作为 Hyperf 的基因。 对于超高速,我们基于 Swoole 协程并在框架设计上进行大量的优化以确保超高性能的输出。 对于灵活性,我们基于 Hyperf 强大的依赖注入组件,组件均基于 PSR 标准的契约和由 Hyperf 定义的契约实现,达到框架内的绝大部分的组件或类都是可替换的。 基于以上的特点,Hyperf 将存在丰富的可能性,如实现 Web 服务,网关服务,分布式中间件,微服务架构,游戏服务器,物联网(IOT)等。 运行环境: Linux, OS X or Cygwin, WSL PHP 7.2+ Swoole 4.4+

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值