0

I have many Cog classes are all similar, and I need to add them to parameterized lists of type Cog based on the class path.Cog_1, Cog_2,..., Cog_N. Is there anyway to use reflection to cast an Object type to specific Cog class if I have the path?

main(){
    List<Cog> CogList = LIsts.newArrayList();
    List<Cog_2> CogList_2 = LIsts.newArrayList();

    CogList.add(createObject("path.to.Cog");
    CogList_2.add(createObject("path.to.Cog_2");

    Class<?> clazz3 = Class.forName("path.to.Cog_3");
    //CogList_3.add(clazz3.cast(result);  Error add (Cog_3) to list cannot be applied to capture <?>
}

public Object createObject(String classPath){
    Class<?> clazz = Class.forName(classPath);
    Constructor<?> cons = clazz.getConstructor();
    return  Object object = cons.newInstance();
}

I'd rather have not have to manually cast each object to type. It works, but but would add in a lot of boiler plate code.

if (result instanceof Cog_10){
    (Cog_10) clazz.cast(result)
}
tima
  • 1,498
  • 4
  • 20
  • 28
MeowMeow
  • 622
  • 1
  • 8
  • 15
  • Reflection basically means you're not going to have nice code. Accept that, or figure out how to do things without reflection. (You usually can.) – Louis Wasserman Jul 23 '17 at 22:49
  • 2
    That cast doesn't make much sense. This looks like an [XY Problem](http://xyproblem.info). You'd be better off discussing *what* you're trying to do rather than *how*. – shmosel Jul 24 '17 at 00:01
  • This is exactly what I've been trying to resolve, except anonymizing variable names. I have a set of base java objects which are client provided and nearly all the same, with more to be added. I have to support this set, along with more similar structures in the near future. The way that was currently handled for similar objects was to have a whole accessing classes for each individual object, which I thought could be avoided. – MeowMeow Jul 24 '17 at 01:14

0 Answers0