简体   繁体   English

Java:循环内变量的几种可能类型

[英]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. 我必须解决工作上的问题,由于我不太精通Java,所以我坚持使用它。

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. 简而言之,我有一个循环,该循环通过Map<String, String>传递Map<String, String>其中值定义了循环内变量类型的名称。 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). 调用对象时,我必须接收ArrayList<String>并将其附加到在项目主类中定义的多数民众赞成(顺便说一句:eclipse不显示任何错误,我会得到运行时异常)。

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 http://en.wikipedia.org/wiki/Generics_in_Java

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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