Java 动态修改注解的属性值

Spring Boot 构建war 部署到tomcat下无法在Nacos中注册服务 因此,当使用外部容器时,如此处的 Tomcat 来部署项目,AbstractAutoServiceRegistration 就不能监听到容器启动事件了,也就不会尝试向服务注册中心注册当前这个微服务,那么注册就失败了,并且也就没有异常信息了。自定义获取获取外部容器端口的方法, 然后监听应用启动事件,当应用被启动时,获取外部容器启动的端口号,然后将这个 port 设置到 NacosAutoServiceReigistration 中。在启动类同级目录,复制下面代码即可(不需要修改,直接构建war即可) 阅读详情

以往来看,注解的属性值一般都是“硬编码”。但最近在开发过程中遇到了需要根据运行环境来设置注解属性值的需求。

举个例子:

package com.das.common.util.csv;

import java.lang.annotation.*;

/**
 * @Author liangmy
 * @Date 2018/10/15
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Header {
    String value() default "";
    double priority() default Double.MAX_VALUE;
    String format() default "";
    HeaderGroupConfigure[] groups() default {};
}
package com.das.common.util.csv;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @Author liangmy
 * @Date 2019/3/17
 */
@Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface HeaderGroupConfigure {
    String headName() default "";
    String groupName();
    double priority() default Double.MAX_VALUE;
    String format() default "";
}

根据HeaderGroupConfigure是否配置priority,修改Header的priority。

 

知识点:

  • 保留策略为 RUNTIME 的注解在运行期是保留的。
  • 出于某些技术原因,Java 虚拟机使用的“真实”注释类的实例是动态代理的实例。
  • Java 注解有一个名为 memberValues 的私有Map,其中存储了属性名称和属性值的k-v对。

基于上述知识点,可以通过反射来访问实例,然后用给定的新值替换现有值。

相关的类:

  • Proxy JDK 动态代理
    可通过其 getInvocationHandler 方法获取注解的代理实例
  • InvocationHandler 调用处理器,每一个被代理的实例都有一个调用处理器
    通过反射获取被代理类的实例的属性值

示例代码:

        // 获取 Header 注解
        Header headerAnnotation = field.getDeclaredAnnotation(Header.class);
        if (null != headerAnnotation) {
            // 获取 Header 中 分组 HeaderGroupConfigure 注解
            HeaderGroupConfigure[] groups = headerAnnotation.groups();
            for (HeaderGroupConfigure group : groups) {
                if (groupNameSet.contains(group.groupName())) {
                    // 计算最终的属性值
                    double groupPriority = Double.MAX_VALUE == group.priority() ? headerAnnotation.priority() : group.priority();
                    // 获取代理处理器
                    InvocationHandler invocationHandler = Proxy.getInvocationHandler(headerAnnotation);
                    // 获取私有 memberValues 属性
                    Field memberValuesField = invocationHandler.getClass().getDeclaredField("memberValues");
                    memberValuesField.setAccessible(true);
                    // 获取实例的属性map
                    Map<String, Object> memberValuesValue = (Map<String, Object>) memberValuesField.get(invocationHandler);
                    // 修改属性值
                    memberValuesValue.put("priority", groupPriority);
                }
            }
        }

略略略

为什么你的PROFINET IRT同步性能不达标?等时模式常见配置误区盘点 本文深入剖析了PROFINET IRT等时模式同步性能不达标的常见原因。文章直击痛点,系统盘点了从硬件兼容性、拓扑组态、过程映像分区分配,到同步OB配置、时序参数调校及带宽管理等关键环节的配置误区,并提供了实用的诊断思路与性能优化清单,帮助工程师精准定位并解决同步抖动、时序混乱等难题。 阅读详情

相关推荐

自动驾驶嵌入式修炼秘籍:理想L9自动驾驶域控制器拆解

自动驾驶嵌入式修炼秘籍:理想L9自动驾驶域控制器拆解

pathfinder888的博客 2547

如何修改String的value值 String深度解读(一)

由一个道题讲起 大家都知道,String在创建后其value是不可变的,因为它的修饰符是 private final ,赋值后既不可变,比如String a =“a”; ...

Daniel的博客 4772

银河麒麟V10 SP1 x86_64架构下离线部署全栈开发环境:Java8+Mysql5.7+Tomcat8实战指南

本文详细介绍了在银河麒麟V10 SP1 x86_64架构下离线部署全栈开发环境的实战指南,包括Java8、Mysql5.7和Tomcat8的安装与配置。通过步骤详解和常见问题排查,帮助开发者在国产操作系统上高效搭建稳定可靠的开发环境,特别适合政务系统和企业级应用部署。

weixin_29230901的博客 372

java自定义注解

Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。 1、元注解 元注解是指注解的注解。包括  @Retention @Target @Document @Inherited四种。 1.1、@Retention: 定义注解的保...

weixin_34192816的博客 912

手把手教你搭建日本亚马逊CVV钓鱼系统(含自动验证功能)

本文详细介绍了电商平台安全防护的关键实践,重点讲解了如何构建自动化风控系统。内容包括基础架构设计、用户行为分析、交易风险评估模型构建、验证机制实现以及系统部署优化,帮助电商平台有效识别和防范安全威胁,同时提升用户体验。

weixin_30952535的博客 813

摄像头visio_最全面弱电智能VISIO图标集(百个),高大上方案就靠这个了

原标题:最全面弱电智能VISIO图标集(百个),高大上方案就靠这个了不会用Visio,Visio画拓扑画的很丑,怎么办?本期sin66小编免费分享一份最全面的弱电智能VISIO图标集(百个)给大家,以后画拓扑、做方案,直接高大上起来!需要本期资料直接看文末!!接下来我们一起看一下这些Visio图标大全:我们从下图可以看出前端设备主要是由枪机,筒机,无线摄像头,半球,球机,USB摄像头等构成,对于绘...

weixin_39644915的博客 1万+

动态修改属性的注解值

思路: 1、先获取需要修改的 Field 2、通过 Field 的方法 getDeclaredField 获取需要修改的注解 3、Proxy.getInvocationHandler(anno) 获取该注解代理实例所持有的 InvocationHandler 4、获取 AnnotationInvocationHandler 的 memberValues 字段 5、获取 memberValuesMap,通过该Map 对注解属性值获取修改

weixin_40017062的博客 2015

2024最新版Anaconda Navigator安装使用指南

本文简要介绍如何下载安装Anaconda Navigator最新版,以及如何使用Python内核搭载来完成应用程序开发。

jackson_lingua的博客 1万+

修改String中的value元素

java中String是不可改变的,因为每次给String赋值的时候都会隐式的new一个String对象,但是String对象中的value还是能改变的 看String的源码中是这么储存数据的: private final char value[]; 因为是final的,value数组不可以更换,只能修改元素的值: /** * 主函数 * * @param

w3741332的博客 3187

WS2812和homeassistant握手

本文学习了WS2812和homeassistant握手,后期会分享更多有趣物联网的操作从而实现对外部世界进行感知,充分认识这个有机与无机的环境,科学地合理地进行创作和发挥效益,然后为人类社会发展贡献一点微薄之力。...

vor234的博客 811

ESP32-C3入门教程 环境篇③——VS Code IDE快速入门

文章目录一、安装Visual Studio Code二、安装扩展三、配置ESP-IDF 插件四、创建工程五、配置工程5.1 选择目标芯片5.2 项目配置六、编译工程七、固件分析七、固件下载八、串口日志九、单步调试 一、安装Visual Studio Code 下载并安装Visual Studio Code 二、安装扩展 左侧扩展 搜索espressif 点击安装 三、配置ESP-IDF 插件 按下F1按键 输入configure esp-idf extension EXPRESS,如果你

8299

java string default values_@RequestParam使用defaultValue属性设置默认值的操作

@RequestParam使用defaultValue属性设置默认值注意设置必须是string类型的,框架自己会做转换@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,@RequestParam(value = "size", required = false) Integer size...

weixin_34837898的博客 3911

MATLAB 与 STK 互联导出导弹轨迹及速度数据(csv导出)

本文介绍了如何通过 MATLAB 脚本连接 STK 提取导弹三维轨迹数据,并以 CSV 格式导出,包含以下关键内容:自动连接 STK 场景;获取所有导弹对象;提取 J2000 坐标系下的位置和速度;加入任务优先级与状态;导出为标准 CSV 文件;

weixin_52370774的博客 778

Java通过反射,如何动态修改注解的某个属性值

我们一眼就可以看到一个有意思的名字:memberValues,这是一个Map,而断点中可以看到这是一个LinknedHashMap,key为注解的属性名称,valglpyuue即为注解的属性值。我们一眼就可以看到一个有意思的名字: memberValues,这是一个Map,而断点中可以看到这是一个 LinknedHashMap,key为注解的属性名称,value即为注解的属性值。如此说来,@TestAnno 注解本身只是个接口,这就意味着它没有任何代码逻辑,那么它的 value 属性究竟是存在哪里的呢?

dituirenwu的博客 2835

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

java中动态修改注解的某个属性值

原文:https://segmentfault.com/a/1190000011213222 昨晚看到一条问题,大意是楼主希望可以动态得建立多个Spring 的定时任务。 这个题目我并不是很熟悉,不过根据题目描述和查阅相关Spring 创建定时任务的资料,发现这也许涉及到通过Java代码动态修改注解的属性值。 今天对此尝试了一番,发现通过反射来动态修改注解的属性值是可以做到的: 众所周知,java/lang/reflect这个包下面都是Java的反射类和工具。 Annotation注...

qq_38122518的博客 5818

pscad IEEE标准系统搭建说明

pscad IEEE标准系统搭建说明,包含典型的IEEE 9节点、14节点、30节点、39节点和118节点系统。内含标准测试系统的原始数据和潮流结果。

JAVA使用变量动态修改注解属性值

JAVA使用变量动态修改注解属性值问题场景反射基础动态修改注解属性值的实现问题场景的修复 问题场景 在使用easyexcel做数据导出时,用到了注解@ExcelProperty标记表头,代码如下: import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.write.style.ColumnWidth; import com.alibaba.excel.annotation.write.sty

q340505050518的博客 7730

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[Java] 通过反射,动态修改注解的某个属性值

转载 原文:https://segmentfault.com/a/1190000011213222 昨晚看到一条问题,大意是楼主希望可以动态得建立多个Spring 的定时任务。 这个题目我并不是很熟悉,不过根据题目描述和查阅相关Spring 创建定时任务的资料,发现这也许涉及到通过Java代码动态修改注解的属性值。 今天对此尝试了一番,发现通过反射来动态修改注解的属性值是可以做到的...

程序猿小河 1795

java动态修改注解属性值

Java动态修改注解属性值 在Java开发中,注解(Annotation)是一种元数据,它可以在源代码中嵌入指示信息,用于描述程序的结构、行为或其他方面的信息。有时候我们需要在运行时动态修改注解的属性值,这在某些场景下会非常有用。本文将介绍如何在Java中动态修改注解属性值,并提供示例代码。 注解的基本概念 在Java中,...

weixin_41442072的博客 753

java中注解动态传参_Java 动态修改注解的属性值

前言以往来看,注解的属性值一般都是“硬编码”。但最近在开发过程中遇到了需要根据运行环境来设置 Retention 为 RUNTIME (运行期保留) 的注解属性值的需求。举个例子:@Table(name="t1")public class Test {private String id;...}对于上述类 Test,其上有一个注解 @Table,需求是这样的: 在测试环境 name 值为"t1",...

weixin_35217123的博客 4376

注解一个mysql属性值_[Java] 通过反射,动态修改注解的某个属性值

昨晚看到一条问题,大意是楼主希望可以动态得建立多个Spring 的定时任务。这个题目我并不是很熟悉,不过根据题目描述和查阅相关Spring 创建定时任务的资料,发现这也许涉及到通过Java代码动态修改注解的属性值。今天对此尝试了一番,发现通过反射来动态修改注解的属性值是可以做到的:众所周知,java/lang/reflect这个包下面都是Java的反射类和工具。Annotation注解,也...

weixin_29107819的博客 155

【java反射修改注解属性】java 通过反射,动态修改注解的某个属性值

java 通过反射,动态修改注解的某个属性值

lzq2357639195的博客 498

【转】java 通过反射,动态修改注解的某个属性值

昨晚看到一条问题,大意是楼主希望可以动态得建立多个Spring 的定时任务。 这个题目我并不是很熟悉,不过根据题目描述和查阅相关 Spring 创建定时任务 的资料,发现这也许涉及到通过Java代码动态修改注解的属性值。 今天对此尝试了一番,发现通过反射来动态修改注解的属性值是可以做到的: 众所周知,java/lang/reflect 这个包下面都是Java的反射类和工具。 Annotation ...

魂-淡 1097

Java 运行时动态修改注解的属性值

Java 运行时动态修改注解的属性值

Jaemon 1884

javabean反射改字段内容_[Java] 通过反射,动态修改注解的某个属性值

昨晚看到一条问题,大意是楼主希望可以动态得建立多个Spring 的定时任务。这个题目我并不是很熟悉,不过根据题目描述和查阅相关 Spring 创建定时任务 的资料,发现这也许涉及到通过Java代码动态修改注解的属性值。今天对此尝试了一番,发现通过反射来动态修改注解的属性值是可以做到的:众所周知,java/lang/reflect 这个包下面都是Java的反射类和工具。Annotation 注解,也...

weixin_42302142的博客 496

Java动态修改注解的属性值

前言 以往来看,注解的属性值一般都是“硬编码”。但最近在开发过程中遇到了需要根据运行环境来设置Retention 为 RUNTIME (运行期保留)的注解属性值的需求。举个例子: @Table(name="t1") public class Test { private String id; ... } 对于上述类Test,其上有一个注解@Table,需求是这样的:在测试环...

HD243608836的博客 5860
上一篇: CentOS 7.4 Web环境部署
下一篇: 货币汇率转换策略
limeOracle
博客等级 码龄10年 11粉丝 566原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值