本文介绍了如何为某些类覆盖 Class<?>.getName()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是能够覆盖我从 CustomClass.class.getName() 和 CustomClass.getClass().getName() 返回的内容

My goal is to be able to override what I get back from CustomClass.class.getName() and CustomClass.getClass().getName()

它应该返回一个自定义值,我认为最好在像

It should return a custom value, which I think is best to define in an attribute like

@NameOverride("Custom.fully.qualified.class.name")
public class CustomClass {}

有没有办法做到这一点?

Is there any way to do that?

推荐答案

Fred 的回答还可以,但他的方面可能会更优雅一些,代码更少,尤其是反射调用更少.抱歉,我更喜欢 AspectJ 原生代码风格,但@AspectJ 注释风格不会太长:

Fred's answer is okay, but his aspect could be somewhat more elegant with less code and especially fewer reflection calls. Sorry, I prefer AspectJ native code style, but @AspectJ annotation style would not be much longer:

String around(Class clazz) : call(public String Class.getName()) && target(clazz) {
    NameOverride nameOverride = (NameOverride) clazz.getAnnotation(NameOverride.class);
    return nameOverride == null ? proceed(clazz) : nameOverride.value();
}

这是完整的源代码.我添加了一个没有注释的类来显示不同的行为,并且还添加了对类定义的限制 - @Target(ElementType.TYPE) - 到注释类.我还显示了包名称和导入:


Here is the full source code. I added a class without annotation to show the different behaviour and also a restriction to class definitions - @Target(ElementType.TYPE) - to the annotation class. I am also showing package names and imports:

package test;

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface NameOverride {
    String value();
}
package test;

public class NormalClass {}
package test;

@NameOverride("Custom.fully.qualified.class.name")
public class CustomClass {}
package test;

public class Main {
    public static void main(String[] args) {
        System.out.println(NormalClass.class.getName());
        System.out.println(CustomClass.class.getName());
        System.out.println(new NormalClass().getClass().getName());
        System.out.println(new CustomClass().getClass().getName());
    }
}
package aspectj;

import test.NameOverride;

public aspect GetNameOverrider {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    String around(Class clazz) : call(public String Class.getName()) && target(clazz) {
        NameOverride nameOverride = (NameOverride) clazz.getAnnotation(NameOverride.class);
        return nameOverride == null ? proceed(clazz) : nameOverride.value();
    }
}

输出:

test.NormalClass
Custom.fully.qualified.class.name
test.NormalClass
Custom.fully.qualified.class.name

这篇关于如何为某些类覆盖 Class<?>.getName()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 20:42