java 方法转化为类,传入“任何”类类型转换为java方法

Okay say I have a class:

public class ExampleClass() {

public void exampleClassMethod(ArrayList 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.

Let's say my custom classes to pass in would be CustomClass1, CustomClass2, CustomClass3.

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?

Thanks.

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;

}

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.

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值