0

I have created a Set of classes which implements a certain interface using Reflections like that:

Reflections reflections = new Reflections("com.project.cookies");
Set<Class<? extends Cookie>> setOfCookies = reflections.getSubTypesOf(Cookie.class);

Now for all cookie i want to bake it eg.:

setOfCookies.stream().forEach(cookie -> cookie.bake());

When I call

cookie.getName() 

I get:

com.project.cookies.Brownie

Brownie class implements the interface Cookie and has a method bake().

I've tried to cast cookie element of type Class<? extends Cookie> into Cookie or Brownie, but I get:

java.lang.ClassCastException: Cannot cast java.lang.Class to com.project.cookies.Cookie

I've also tried

cookie.getSuperclass().getConstructor(Cookie.class).newInstance()

but ite gives me some weird type capture of ? super capture of ? extends Cookie and i cannot call method on it.

My question is how can I access bake() method having a <Class<? extends Cookie>?

  • 3
    `Class` and `Cookie` is not the same. Instance of `Class` holds metadata *about Cookie* type. You can think of it as paper on which we have written list all fields, methods, constructors, etc. belonging to Cookie type. BUT IT IS NOT `Cookie` itself (you can't eat that paper and expect same results as eating proper Cookie). It looks like you want to *use* `Class` to call `bake()` method, but [while it is possible](https://stackoverflow.com/q/2407071) it sill *require an instance of Cookie/Brownie* on which that method will be called. – Pshemo Dec 03 '22 at 18:28
  • 1
    Your `setOfCookies` is not really a set of cookies. More like a `setOfCookieRecipes` – knittl Dec 03 '22 at 19:25
  • Thank you @Pshemo, one of the answer in the topic you mentioned helped me. The code below did the job: Class clazz = Class.forName(cookie.getName()); Method method = clazz.getDeclaredMethod("bake"); Object obj = clazz.getDeclaredConstructor().newInstance(); method.invoke(obj); – cookiezaurus Dec 03 '22 at 23:57

0 Answers0