0

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

example:

public void Transfer (class c){ class.Search(); } 
3
  • 1
    Yes you can.. You've got the syntax wrong though :) Commented Dec 28, 2015 at 9:52
  • Your question is correct, the answer is "yes". But your example is syntactically incorrect and completely confusing. Commented Dec 28, 2015 at 9:53
  • Ok thanks for your answers. How can i write a correct method??? Commented Dec 28, 2015 at 9:56

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.