检查类是否代表CDI 1.2

Otá*_*cia 6 java cdi weld

在CDI 1.2中,有一种方法可以检查类实例是否被代理?我需要这个,因为我需要获取原始类的名称,而不是代理名称.

@Inject Bean bean;

public void sysout() {
    // will print something like com.Bean$$Weld9239823
    System.out.println(bean.getClass()); 

    // I don't know how to check if the bean instance if a proxy or real class instance
}
Run Code Online (Sandbox Code Playgroud)

使用Weld类我可以完成这项工作:

public void sysout() {
    // will print true because this is a proxy
    System.out.println(ProxyObject.class.isAssignableFrom(bean)); 

    // will print com.Bean
    System.out.println(((TargetInstanceProxy) bean).getTargetInstance());
}
Run Code Online (Sandbox Code Playgroud)

在CDI 1.1中,没有方法可以做到这一点.我在CDI 1.2文档中搜索如果添加了一个方法,但我没有找到任何东西.

所以...我想念一些东西和CDI 1.2有一种获取原始类名和实例的方法吗?或者,如果没有,有一个平原在附近功能添加此功能?

Jam*_*ble 0

这是一个可怕的黑客,但对于 Weld (以及可能的其他实现),您可以检查类名是否包含 "Proxy": possibleProxy.getClass().getSimpleName().contains("Proxy")。我仅将它用于记录目的,以获得包装类名称的清理版本:

/**
 * Get the actual simple name of the objects class that might be wrapped by
 * a proxy. A "simple" class name is not fully qualified (no package name).
 *
 * @param possibleProxy an object that might be a proxy to the actual
 * object.
 * @return the simple name of the actual object's class
 */
public static String getActualSimpleClassName(final Object possibleProxy) {
    final String outerClassName = possibleProxy.getClass().getSimpleName();
    final String innerClassName;
    if (outerClassName.contains("Proxy")) {
        innerClassName = outerClassName.substring(0, outerClassName.indexOf('$'));
    } else {
        innerClassName = outerClassName;
    }
    return innerClassName;
}
Run Code Online (Sandbox Code Playgroud)