5

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.

0

4 Answers 4

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

    return "some string";
}

void method1(Class c) 
{
   // Some stuff.
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1 previous solution was better if user wants to pass two different paramerters like : Userdefinedclass1.class,Userdefinedclass obj
thanks for the reply if i have to call this function is this the syntax (eg:if Animal is my class) methodName(Animal,Animal anim)
1

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

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.