如何为某些类重写Class<?> .getName()? [英] How do I override Class<?>.getName() for certain classes?

查看:128
本文介绍了如何为某些类重写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 {}

有什么办法吗?

推荐答案

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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆