java 重载 泛型,如何在Java中使用泛型参数重载方法?

该博客讨论了在Java中如何处理泛型参数导致的方法重载问题。由于类型擦除,直接使用泛型参数进行方法重载会导致编译错误。文章提出了两种解决方案:一是更改方法名以区分,二是通过接口实现双态调度。对于后者,文章给出了一个例子,展示了如何创建不同的FooInterface实现来处理不同类型的List参数。
摘要由CSDN通过智能技术生成

How to overloading method with generic parameter in java?

Say I have following class

import java.util.List;

public class C {

public void foo(List a){

}

public void foo(List b){

}

}

This gives compilation error and rightly so as erasure is doing it's job and removing the type information, so after compilation both the methods will have same parameter of list only.

If I don't want to use

public void foo(List a){

}

Is there any other way to overload the method foo()?

解决方案

Two approaches that you should follow.

Change the method names.

Use an Interface for this purpose.

then either put the foo code in the objects themselves, or use

double-dispatch (depending on your design paradigm and taste).

With code in objects that would be:

public interface FooInterface{

void foo();

}

public class Foo

{

public void abc(Collection objects)

{

for(T object: objects)

{

object.foo();

}

}

}

public class FooString implements FooInterface {

public void foo(){

// do foo for String

}

}

public class FooInteger implements FooInterface {

public void foo(){

// do foo for Integer

}

}

If Domain contains your logic.

With a double dispatch, you would pass the "FooInterface" to the foo method, and on the handler call the appropriate method depending on the type.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值