简体   繁体   中英

Java Method with generic class as argument

It is possible write a method in java with generic class with argumet??

example:

public void Transfer (class c){
    class.Search();
}

Yes, you would need to do something like so:

public class Foo<T> {
    public void Transfer(T c) {
        c.Search();
    }
}

Since you seem to want to invoke a specific method, you might want to define an interface which provides the methods you are after, and bind the generic constraint with it:

public interface MyInt {
    void Search();
}

....
public class Foo<T extends MyInt> {
    public void Transfer(T c) {
        c.Search();
    }
}

Alternatively:

public class Foo {
    public void Transfer(MyInt c) {
        c.Search();
    }
}

The last example does away with generics and uses interfaces, which can sometimes yield code which is easier to follow, depending on what you are trying to achieve.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM