mercredi 26 septembre 2018

Java: Get class type of return object of generic supplier

Let's assume the following definition is given:

final Supplier<MyClass> supplier = MyClass::new;

Is there a way I can get MyClass.class without actually invoking .get() on the supplier?

Why? I have to know the specified class to make some logical decisions. Based on this, I might need to find another constructor in MyClass which has a parameter and the only knowledge I have of the target class is a supplier of this type. Of course I could just invoke .get() and go from there, like this:

final MyClass obj = supplier.get().getClass().getConstructor(MyParameter.class).newInstance(..);

But using this before doing my intermediate steps might result in an unnecessary object creation





Aucun commentaire:

Enregistrer un commentaire