我试图在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.
更多推荐
发布评论