Passing in “any” class type into a java method

后端 未结 3 2021
我寻月下人不归
我寻月下人不归 2021-01-26 11:21

Okay say I have a class:

public class ExampleClass() {
    public void exampleClassMethod(ArrayList abcdefg> arrList) {
        ....
             


        
相关标签:
3条回答
  • 2021-01-26 11:58

    Use List<Object> to accept any List object in the method.

    public void exampleClassMethod2(List<Object> custClassArg) {
        ....
    }
    

    use List instead of ArrayList as it give more flexibility.

    Also you can use List<? extends CustomClass> if all the other customClasses extends from a base type.

    0 讨论(0)
  • 2021-01-26 11:58

    For the second part

    1)tester(Object s) method will accept all Types of Object because any Object in Java internally inherits from java.lang.Object. So tester((Object) abc); not required at all.

    2)Typecast abc to CustomClass1 using CustomClass1 custom = (CustomClass1)abc. I hope it works.

    3)You can use instanceOf operator but I guess this is lot of overhead for the developer & makes the code unreadable. Use it only if required.

    0 讨论(0)
  • 2021-01-26 12:05

    Any ArrayList:

    public void example( ArrayList<?> arr ) { ...
    

    Any type of CustomClass:

    public void example( ArrayList< ? extends CustomClass> arr ) { ...
    

    Edit: 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();
    }
    

    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.

    0 讨论(0)
提交回复
热议问题