0

I would like to do something like this in java 8:

public void example(Class clazz) {
    MyClass<clazz> myObj = new MyClass<clazz>();
}

But I'm getting "cannot find symbol: symbol class clazz location: "

Is this possible? Thanks!

anonymouse
  • 639
  • 1
  • 8
  • 18

3 Answers3

1

Generic type parameters must be type names, not variable names.

Declare a generic type parameter for your method, and use it in your parameter and variable declaration.

public <T> void example(Class<T> clazz) {
    MyClass<T> myObj = new MyClass<T>();
}

Generally one uses single capital letters as type variables, e.g. T, to distinguish them easily from normal variables, e.g. clazz.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • What is the `Class clazz` part good for? – Andrey Tyukin Feb 05 '18 at 21:37
  • @AndreyTyukin It is the standard way to get access to a type at runtime. See [How to get a class instance of generics type T](https://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t) and [Get generic type of class at runtime](https://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime). – rgettman Feb 05 '18 at 21:40
  • @AndreyTyukin you could get the constructor from clazz and the do newInstance – anonymouse Feb 05 '18 at 21:44
  • @rgettman Okay, figured it would probably be something like this. Thanks! – anonymouse Feb 05 '18 at 21:45
  • Well, yes, this is of course true. It's just not used in the method in any meaningful way. And, given that the OP hasn't quite figured out the difference between method arguments and generics, it might lead to the false impression that one always needs to carry around a `Class` to parameterize something by `T`. – Andrey Tyukin Feb 05 '18 at 21:45
  • 2
    @anonymouse "you could get the constructor from clazz and the do newInstance" it would be preferable to pass a `Supplier` instead, if that's what you're trying to do. – Andy Turner Feb 05 '18 at 21:48
0

You can do this :

public void example() {
    MyClass<Class> myObj = new MyClass<Class>();
}

You can not put variables inside <>

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
L Y E S - C H I O U K H
  • 4,765
  • 8
  • 40
  • 57
0

Since you want clazz to be a type, you must pass it as a type parameter:

public <T> void example() {
    MyClass<T> myObject = new MyClass<T>();
}
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93