传入“任何”类类型转换为java方法 [英] Passing in "any" class type into a java method
问题描述
好吧,我有一个类:
public class ExampleClass() {
public void exampleClassMethod(ArrayList<CustomClass> abcdefg> arrList) {
....
}
public void exampleClassMethod2(ArgumentToTakeInAnyCustomClass custClassArg) {
....
}
}
现在我想能够将任何对象的任何数组列表传递给该类的方法。
Now I want to be able to pass in any array list of any objects into that method in that class.
假设我要传入的自定义类是CustomClass1,CustomClass2,CustomClass3。
Let's say my custom classes to pass in would be CustomClass1, CustomClass2, CustomClass3.
我如何设置该方法来接受我传入的任何ArrayList?此外,让我说,我只是想传递一个类本身,如在第二个示例方法,我该怎么做?
How would I set up that method to accept any ArrayList that I pass in? Also, lets say I just wanted to pass in one of those classes themselves, as in the second example method, how would I do that?
谢谢。
public void testerMethodInitiater() {
CustomClass1 abc = new CustomClass1();
tester((Object) abc);
}
public static void tester(Object abc) {
//do stuff
System.out.println(abc);
if(abc instanceof CustomClass1) {
System.out.println("This is a CustomClass1");
}
(I need to tell the program to create a new CustomClass1 here if it's a CustomClass1) tester;// = new Object<Universalvars.getClassInUse()>;
}
$ b ,但我不知道如何做一个新的CustomClass1在这个时候,除非我做了一个条件语句命名可能发生的所有可能性,我试图避免。
Code above prints out that the object is an instance of CustomClass1, but I'm not sure how to make a new CustomClass1 at this time unless I did a conditional statement naming all possibilities that could take place which I'm trying to avoid.
推荐答案
任何 ArrayList
:
public void example( ArrayList<?> arr ) { ...
任何类型的 CustomClass
:
public void example( ArrayList< ? extends CustomClass> arr ) { ...
您可以使用反射创建任何类型的新对象:
For the second half of your question, you can create a new object of any type with reflection:
public void tester( Object obj ) {
Object obj2 = obj.getClass().newInstance();
}
这需要 Object
有一个零参数构造函数。我不知道你为什么要这样做。你可能想要实现 clone()
,或者你可能想更多地考虑你的真正目标。通常在 CustomClass
中添加多态方法来解决这些我有什么类问题。
This requires that the class of Object
has a zero-argument constructor. I don't know why you'd want to do this however. You might want to implement clone()
instead, or you might want to think a little more about your real goal at the end of all this is. Usually adding a polymorphic method to CustomClass
solves these "what class do I have" type questions.
这篇关于传入“任何”类类型转换为java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!