如何在比较Java泛型时避免字符串硬编码



是否有更好的方法,我可以比较Type java通用其他硬编码的String ?

在这个方法中,我想将硬编码字符串交换为对类的引用:

    @Override
    public Object fromBody(TypedInput body, Type type) throws ConversionException {
        if (!type.toString().equals("com.package.app.LstMdl<com.package.app.AdMdl>")) { //I would like not to use this String
            //do sth
        }
        return super.fromBody(body, type);
    }

我试着把它换成这个:

        @Override
        public Object fromBody(TypedInput body, Type type) throws ConversionException {
            if (!(type.equals(LstMdl.class) && ((LstMdl)type).data.getClass().equals(AdMdl.class))) {
                //do sth
            }
            return super.fromBody(body, type);
        }

但它不起作用。第一个解决方案很好,但是有没有更优雅的方法呢?

try this:

if (!(type.equals(LstMdl.class) && ((ParameterizedType)type).getActualTypeArguments()[0].equals(AdMdl.class))) {

我们可以尝试像这样用类来构建String:

String expectedTypeStr = String.format("%s<%s>", LstMdl.class.getName(), AdMdl.class.getName());
if (!type.toString().equals(expectedTypeStr)) {