0

I have a basic question regarding Java generics. I have a method that takes this as an argument:

public id findKey(List<String> ids, CustomClass clazz) {
    repos.findID(ids, clazz);
}

I then want to use a java generic class as an argument for another method:

repos.findID(ids, clazz);

but my findID method needs a java generic class instead of clazz. How do I get my clazz argument from the findkey parameter and turn it to a generic class? If I do this:

public id findKey(List<String> ids, Class<T> clazz) {
    repos.findID(ids, clazz);
}    

I get an error because it won't recognize my T.

I'm at loss at how this stuff works and would appreciate any help.

Edit: Solved it. I can use ? or explicitly state a class type that I wanted and it accepted it.

4
  • 6
    Unless you actually need T elsewhere in your method, Class<?> is sufficient. Otherwise, just define a type variable: public <T> id findKey(.... Commented Feb 15, 2017 at 12:20
  • Thanks, I solved it like 10 seconds after posting this. Commented Feb 15, 2017 at 12:21
  • 1
    then please answer it yourself - maybe it helps someone else Commented Feb 15, 2017 at 12:22
  • @CarlosHeuberger indeed: stackoverflow.com/help/self-answer Commented Feb 15, 2017 at 12:23

2 Answers 2

1

There are two options:

  • define your type as unknown

    public id findKey(List<String> ids, Class<?> clazz)
    
  • define a type variable

    public <T> id findKey(List<String> ids, Class<T> clazz)
    
Sign up to request clarification or add additional context in comments.

Comments

1

Use public id findKey(List<String> ids, Class<?> clazz) and read more about wildcards

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.