user1651070
user1651070

Reputation: 93

To create generic method for various User defined class in java

I am trying to achieve the following: I have this method

public String methodName(Userdefinedclass.class,Userdefinedclass obj)
{

//some code 
.........
method(Userdefinedclass.class);
method2(obj);

}

I want to generalise this method.

The challenge is that the argument here is user defined, i.e it can change. So please help.

Upvotes: 5

Views: 1899

Answers (4)

Juvanis
Juvanis

Reputation: 25950

public <T> String methodName(Class<T> c, T obj) 
{
    method1(c);
    method2(obj);

    return "some string";
}

void method1(Class c) 
{
   // Some stuff.
}

Upvotes: 6

jlordo
jlordo

Reputation: 37823

This keeps your method signature intact:

public <T> String  methodName(Class<T> c, T obj)
{
   method(c);
   method2(obj);
}

but i would use ivanovic's answer.

Upvotes: 1

Jatin
Jatin

Reputation: 31744

Generics is type erasure so you cannot have .class of Generic type. That is becaue generics are erased in this case to Object type. Hence `T.class' wont work

So instead use Class<T> to get the class and then work along

Upvotes: 1

Konza
Konza

Reputation: 2173

If you want to generalize the parameters used in the function you can create an empty interface and force the userDefinedClass to implement it.. Or You can use T for achiving this

Upvotes: 0

Related Questions