Reputation: 93
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
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
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
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
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