0

我正在尝试将作用域添加到我的依赖注入包中。所以我想我会定义一个这样的范围

public interface Scope {

    <T> T apply(T type);

    <T> T resolve(Class<T> type);

}

然后像这样进行一个实现该接口的枚举:

public enum Scopes implements Scope {

    DEFAULT,

    SINGLETON {

        private final Map<String, Object> singletons = new HashMap<String, Object>();

        @Override
        public <T> T apply(T object) {
            if (!singletons.containsKey(object.getClass().getName())) {
                singletons.put(object.getClass().getName(), object);
                System.out.println("Applied for: " + object.getClass().getName());
            }
            return object;
        }

        @Override
        @SuppressWarnings("unchecked")
        public <T> T resolve(Class<T> type) {
            Object object = singletons.get(type.getClass().getName());
            System.out.println("Resolved for: " + type.getClass().getName());
            return object == null ? null : (T) object;
        }

    };

    @Override
    public <T> T apply(T object) {
        return object;
    }

    @Override
    public <T> T resolve(Class<T> type) {
        return null;
    }

}

但是,当使用这样的代码时:

System.out.println("Real type: " + type.getName());
T result = scope.resolve(type);

由于某种奇怪的原因,输出的解析变为java.lang.Class但实际类型正确输出。

4

1 回答 1

4

那不是月亮虫。

由于某种奇怪的原因,输出的解析变为 java.lang.Class 但实际类型正确输出。

因为Class#getName()is java.lang.Classwhenthis是 a Class<Class>,而 class oftype总是Class- 因为这就是你type在方法签名中定义的类!

您已经一个Class实例(type,还记得吗?)所以删除额外的getClass()调用。更改此行:

System.out.println("Resolved for: " + type.getClass().getName());

对此:

System.out.println("Resolved for: " + type.getName());
于 2013-09-28T04:30:04.300 回答