java动态添加注解_运行程序向一个Java类中动态添加注解。

/**

* 根据CopyModel对未完成的Java文件(class类)添加包名、import、extends、implements、注解等

*

* @param oldFile

* @param classDecorateModel

*

* 组件名

* 文件名

* 包名

* 父类全名(包括包名)

* 方法字符串

* String[] 接口全名(包括包名)数组

* String[] import 全名(包括包名)数组

*

* Map>

* Map>

* Map>

*

* @return

*/

public static File decorateFileByCopyModel(File oldFile, ClassDecorateModel classDecorateModel){

String oldFileName = oldFile.getName().replace(".java", "");

// 新建文件的名

String tempFileName = oldFileName + System.currentTimeMillis();

String absolutePath = oldFile.getAbsolutePath();

absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf("\\"));

File newFile = new File(absolutePath + "\\" + tempFileName);

try {

newFile.createNewFile();

// 读取文件到FileInputStream中

FileInputStream fileInputStream = new FileInputStream(oldFile);

// 读取FileInputStream到InputStreamReader中,然后再读取到BufferedReader中

BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

// 新建的文件绑定到FileOutputStream上

FileOutputStream fileOutputStream = new FileOutputStream(newFile);

// 把FileOutputStream绑定到PrintWriter上

PrintWriter printWriter = new PrintWriter(fileOutputStream);

String packageName = classDecorateModel.getPackageName(), fileName;

if(packageName == null || "".equals(packageName)){

// 按行从BufferedReader中读取代码

String thisLine, packageLine;

while((thisLine = bufferedReader.readLine()) != null){

// 输出包名和导入项

if(thisLine.startsWith("package ")){

packageLine = thisLine.substring(0, thisLine.indexOf(";"));

packageName = packageLine.replace("package ", "");

break;

}

}

}

bufferedReader.close();

// 获取源文件的class对象

fileName = oldFile.getName().substring(0, oldFile.getName().indexOf("."));

Class> classFile = Class.forName(packageName + "." + fileName);

// 文件中所有注解 Map>>

Map>> existsNameAnnotationMap = ClassAnnotationParse.generateAnnotationParse((Class>)classFile);

fileInputStream = new FileInputStream(oldFile);

BufferedReader inputBufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

// 导入语句

List importStrList = new ArrayList();

String[] importArray = classDecorateModel.getImportArray();

if(importArray != null){

for(String importStr : importArray){

importStrList.add(importStr);

}

}

// 父类名

String parentClassName = classDecorateModel.getParentFullClassName();

String simpleParentName = null;

if(parentClassName != null && !"".equals(parentClassName)){

// 添加到import语句

if(!importStrList.contains("import " + parentClassName + ";")){

importStrList.add("import " + parentClassName + ";");

}

simpleParentName = parentClassName.substring(parentClassName.lastIndexOf(".") + 1, parentClassName.length());

}

// 接口名

String[] interfaceNameArray = classDecorateModel.getImplementsArray();

StringBuffer interfaceBuffer = null;

if(interfaceNameArray != null){

interfaceBuffer = new StringBuffer();

String simpleInterfaceName;

for(String interfaceName : interfaceNameArray){

simpleInterfaceName = interfaceName.substring(interfaceName.lastIndexOf(".") + 1, interfaceName.length());

if(!interfaceBuffer.equals("")){

interfaceBuffer.append(",");

}

interfaceBuffer.append(simpleInterfaceName);

// 添加到import语句

if(!importStrList.contains("import " + interfaceName + ";")){

importStrList.add("import " + interfaceName + ";");

}

}

}

// Map

// Map

// Map

Map toAddAnnotationModelMap = classDecorateModel.getAnnotationMap();

Map toAddAttrMap = null;

AnnotationModel[] toAddAnnotationArray = null;

Map> existsAnnotationMap = null, newAnnotationMap = null;

Map existsAnnoAttrMap = null, newMap = null;

boolean existsAnnoFlag = false, existsAnnoAttrFlag = false;

String toAddSimpleAnnoName, methodNamePara = null, attributeName, packClassName;

if(toAddAnnotationModelMap != null){

String toAddKey;

for(Entry toAddAnnotationModelEntry : toAddAnnotationModelMap.entrySet()){

// 本类所有要添加的注解

toAddAnnotationArray = toAddAnnotationModelEntry.getValue();

// 循环注解

for(AnnotationModel annotationModel : toAddAnnotationArray){

// 添加到import列表中

if(!importStrList.contains("import " + annotationModel.getAnnotationFullName() + ";")){

String fa = annotationModel.getAnnotationFullName();

fa = "import " + fa + ";";

importStrList.add(fa);

}

}

// key 属性 方法 或类本身

toAddKey = toAddAnnotationModelEntry.getKey();

// Map

if(toAddKey.contains("Method-")){

// 方法名##参数类型,参数名-参数类型,参数名

methodNamePara = toAddKey.split("-")[1];

// 获取类中该方法本来就有的注解 Map>

existsAnnotationMap = existsNameAnnotationMap.get(methodNamePara);

for(AnnotationModel toAddAnnotationModel : toAddAnnotationArray){

// 类中是否已经含有要添加的注解类

existsAnnoFlag = false;

existsAnnoAttrFlag = false;

if(existsAnnotationMap != null){

for(Entry> existsAnno

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,动态添加字段注解通常是通过反射(Reflection)API实现的。反射允许程序运行时检查和修改类、接口、字段、方法等的信息。以下是一个简单的例子,展示如何动态添加`@Deprecated`注解: ```java import java.lang.reflect.Field; import java.lang.annotation.Annotation; public class DynamicAnnotationExample { public static void addDeprecatedAnnotation(String className, String fieldName) throws Exception { // 获取目标类的Class对象 Class<?> clazz = Class.forName(className); // 获取字段 Field field = clazz.getDeclaredField(fieldName); // 检查是否已存在注解,如果已存在,则不需要再次添加 if (!field.isAnnotationPresent(Deprecated.class)) { // 获取注解类型 Class<? extends Annotation> annotationType = Deprecated.class; // 创建注解实例 Annotation annotation = annotationType.newInstance(); // 添加注解到字段 field.setAccessible(true); // 如果是private,需要设置为可访问 field.addAnnotation(annotation); } } public static void main(String[] args) throws Exception { addDeprecatedAnnotation("com.example.MyClass", "myField"); // 替换为你的类名和字段名 } } ``` 在这个例子中,我们首先获取指定类和字段的`Class`对象,然后检查该字段是否已经应用了`@Deprecated`注解。如果没有,我们创建一个新的`Deprecated`注解实例,并使用`addAnnotation`方法将其添加到字段上。 请注意,这只是一个基本示例,实际使用时可能需要处理异常,并且动态添加注解可能违反某些设计原则或引发安全问题,因此通常只在特定场景下(如测试工具或特定框架内部)使用。此外,对于私有字段,`setAccessible(true)`会暴露潜在的安全漏洞,仅在必要时使用
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值