vksd vksd - 10 months ago 47
Java Question

Generic methods to whom I can pass String parameter

I have a string-like class

. To its methods, I would like to pass generic types T, where T can either be a string, or an object of
. What I have done so far is put the methods of the String class that I use (such as
charAt(), size()
) into an interface
, and written something like this:

class myString implements myInterface{
public <T extends myInterface> void mymethod(
T inputString){

What I want is that
can be either a String or a

However, I get an error that says
String is not a valid type for T

What I am doing wrong?

PS: This is my first question on Stack, so pl. bear with me.


You should use java.lang.CharSequence interface instead of MyInterface to define your own string class. And your method reference the generic type should be:

public <T extends CharSequence> void mymethod(T inputString) {

BTW, CharSequence does not have size() method, so you should use length() instead.

Refer to