将T作为参数传递给Java,有条件地创建Generic(Pass T as a parameter to to conditionally create Generic in Java)

编程入门 行业动态 更新时间:2024-10-26 22:30:02
将T作为参数传递给Java,有条件地创建Generic(Pass T as a parameter to to conditionally create Generic in Java)

我试图在Java中有条件地创建一个Generic实例,其中类型作为参数传递。 像这样的东西:

private void doStuff(somethingThatDescribesWhatTShouldBeHere) { ArrayList<thetypeTthatwaspassedin> = new ArrayList<thetypeTthatwaspassedin> ... rest of logic }

我无法弄清楚我的生活,如果没有ArrayList<T>回应我,T参数应该是什么样子。

我们的想法是,如果T是一个字符串,那么ArrayList<String>就会被实例化。如果它是Foo,那么ArrayList<Foo>会在内部实例化。

请帮忙

I am trying to conditionally create a Generic instance in Java where the type is passed as a parameter. Something like this:

private void doStuff(somethingThatDescribesWhatTShouldBeHere) { ArrayList<thetypeTthatwaspassedin> = new ArrayList<thetypeTthatwaspassedin> ... rest of logic }

I cannot figure out for the life of me what the T parameter should look like without the ArrayList<T> screaming back to me.

The idea is if T is a string then an ArrayList<String> is instantiated .. if it is Foo then an ArrayList<Foo> is instantiated instead inside.

Please help

最满意答案

好吧,只需使doStuff泛型:

// If you can, pass a parameter of type T : private <T> void doStuff(T something) { ArrayList<T> = new ArrayList<T>(); ... rest of logic } // so it can be called like that : YourType param = ...; foo.doStuff(param); // If you can't pass a parameter of type T, you'll have // to explicitly tell the compiler which type to use : foo.<YourType>doStuff();

如Stijn Geukens暗示的那样传递Class<T>也是一种避免丑陋的后一种语法的常用方法,如果你不需要传递一个实际的对象。

Well, just make doStuff generic :

// If you can, pass a parameter of type T : private <T> void doStuff(T something) { ArrayList<T> = new ArrayList<T>(); ... rest of logic } // so it can be called like that : YourType param = ...; foo.doStuff(param); // If you can't pass a parameter of type T, you'll have // to explicitly tell the compiler which type to use : foo.<YourType>doStuff();

Passing Class<T> as hinted by Stijn Geukens is also a common way of avoiding the ugly, latter syntax if you don't need to pass an actual object.

更多推荐

本文发布于:2023-08-01 16:42:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1361275.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   参数   Java   Generic   create

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!