简体   繁体   中英

Java: Several possible types for a variable inside of a loop

I have to solve a problem for work and since I'm not very fluent in java I'm stuck with it.

To make it short, i have a loop that passes through a Map<String, String> where the value defines the name of the variable's type that is inside of the loop. I tried to do a workaround in may ways; i used reflection, and some generic classes, but the problem is everytime the same: the program cant access the methods of that generated object, since im not able to determine its type. When the object is called, i have to receive an ArrayList<String> and append that to one, thats defined in the main class of the project (Btw: eclipse does not show any errors, i get a runtime exception).

So the question is: How am i able to allocate a variable with a dynamic type from a string ( i assume with reflection ) inside of a loop and access methods from the object thats stored in it?

So far it sounds like it should be something like this:

for (Map.Entry<String, String> entry : myMap.entrySet()){

    Class<?> clazz = Class.forName(entry.getValue());
    ADBBean bean = (ADBBean)clazz.newInstance();
    Method method = clazz.getMethod("methodName", String.class, Integer.class, etc);
    method.invoke(bean, "blah", 145);
}

I think you are looking for Templating/ generic programming. http://en.wikipedia.org/wiki/Generics_in_Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM