使用匿名类创建参数化类型对象 [英] Creating parameterized type object using anonymous class

查看:99
本文介绍了使用匿名类创建参数化类型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但我刚刚看到一个问题,要求如何为泛型类型创建一个Type变量。共识似乎是你应该有一个返回该类型的虚拟方法,然后使用反射来获取它(在这种情况下,他想要 Map< String,String> )。像这样:

  public Map< String,String> dummy(){throw new Error(); } 

类型mapStringString = Class.forName(ThisClass)。getMethod(dummy)。getGenericReturnType();

我的问题是,没有使用过多的反射,难道你不能这样做:

 类型mapStringString = new ParameterizedType(){
public Type getRawType(){
return Map.class;
}

public Type getOwnerType(){
return null;
}

public Type [] getActualTypeArguments(){
return new Type [] {String.class,String.class};
}
};

这个工作吗?如果不是,为什么不呢?如果它存在一些危险/问题,那么它会发生什么(除了能够返回某些类型,如 Integer< String> ,这显然是不可能的。

解决方案

然而,对于大多数应用程序来说,例如使用第一种方法创建一个对象 type1 ,并且 type2 code>>然后 type1.equals(type2)会返回true(因为第一个方法返回一个正确实现equals方法的对象),但是 type2.equals(type1)会返回false(因为在第二种方法中,您没有重写equals方法,并且正在使用来自对象)。



相同的推理适用于其他(有时是有用的方法),例如 toString hashCode 等。第二种方法没有提供这些有用的实现。


This might be a stupid question, but I just saw a question asking how to create a Type variable for a generic type. The consensus seemed to be that you should have a dummy method returning that type, and then use reflection to get it (in this case he wanted Map<String, String>). Something like this :

public Map<String, String> dummy() { throw new Error(); }

Type mapStringString = Class.forName("ThisClass").getMethod("dummy").getGenericReturnType();

My question is, not having used reflection that much, couldn't you just do something like:

Type mapStringString = new ParameterizedType() {
    public Type getRawType() {
        return Map.class;
    }

    public Type getOwnerType() {
        return null;
    }

    public Type[] getActualTypeArguments() {
        return new Type[] { String.class, String.class };
    }
};

Would this work? If not, why not? And what are some of the dangers/problems if it does (besides being able to return some Type like Integer<String> which is obviously not possible.

解决方案

Sure you could, and for most applications it would probably be sufficient.

However, using the first method, you get a more refined object. Let's say for instance that you create an object type1 using the first method, and type2 using the second method. Then type1.equals(type2) would return true (since the first method returns an object that properly implements the equals-method) but type2.equals(type1) would return false (since in the second method, you haven't overridden the equals-method, and are using the implementation from Object).

Same reasoning applies to other (sometimes useful methods) such as toString, hashCode etc. The second method does not provide useful implementations of these.

这篇关于使用匿名类创建参数化类型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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