Reputation: 31
Is there a way to implement in Java Generics method that the type is any type that has specific function name (not in inheritance ) ?
Upvotes: 0
Views: 391
Reputation: 1988
If I understand your question correctly, it looks like you are trying to use generics to only allow for types that implement a method with a certain name. They're called methods, not functions, in Java.
Unfortunately, this isn't possible directly. The best thing you can do is create an interface that contains the required method, have your classes containing the method implement it, and then use a generic type constraint for that specific interface type:
public interface SomeInterface {
int doSomething(int x, int y);
}
Do note that this requires that the entire signature be the same (not only the same name, but also the same parameters and a compatible return type). Your code would then look like this:
public class GenericClass<T extends SomeInterface> {
Also note that this will only work perfectly if all the classes you're using were made by you. If you're also using classes by someone else that have the same method signature, it should be possible to make your own class that extends the library class and is declared as implementing the interface, and use that class instead of the library class.
If you really need to check for methods that have the same name but not the same signature, there may be another way to do it using reflection. If you need that, please let me know in a comment.
Upvotes: 1