首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取作为文件输入的参数类型

获取作为文件输入的参数类型
EN

Stack Overflow用户
提问于 2017-07-18 18:58:22
回答 1查看 158关注 0票数 0

我有一个文本文件,作为参数传递给我的程序。该文件包含类名和参数,我应该实例化它们:

代码语言:javascript
复制
Home:
SmartMeter:30,false

我想使用反射来创建实例,但我不知道如何从文件中获得参数的实际类型。在得到它之后,我想将它们与这个类的所有构造函数的参数类型进行比较,并选择正确的一个。下面是我到目前为止编写的代码:

代码语言:javascript
复制
    Scanner scan = new Scanner(new File(args[0]));
    String[] classNameAndParameters;
    String[] parameters;

    while (scan.hasNextLine()) {
        classNameAndParameters = scan.nextLine().split(":");
        Class<?> c = Class.forName(classNameAndParameters[0]);

        // i check for the length too because it throws arrayoutofbounds exception
        if (classNameAndParameters.length > 1 && classNameAndParameters[1] != null) {
            parameters = classNameAndParameters[1].split(",");


            // get all constructors for the created class
            Constructor<?>[] constructors = c.getDeclaredConstructors(); 

            for(int i = 0; i < constructors.length; i++) {
                Constructor<?> ct = constructors[i];
                Class<?> pvec[] = ct.getParameterTypes();

                for (int j = 0; j < pvec.length; j++) {
                    System.out.println("param #" + j + " " + pvec[j]);
                }
            }
            //i should match the parameter types of the file with the parameters of the available constructors


            //Object object = consa.newInstance();
        } else {
            // default case when the constructor takes no arguments
            Constructor<?> consa = c.getConstructor(); 
            Object object = consa.newInstance();
        }
    }

    scan.close();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-19 04:43:26

您需要在文本文件中指定参数类型,否则Java不可能解决运行时中某些参数的模糊性。

例如,如果您有类Book:

代码语言:javascript
复制
public class Book {
  public Book() {
  }

  public Book(Integer id, String name) {
  }

  public Book(String idx, String name) {
  } 
}

你提供了书: 30,饥饿小游戏

代码如何知道要选择哪个构造函数,因为30是一个合法整数,同时也是合法字符串?

假设没有一个构造函数是模棱两可的,下面是如何做到这一点:

代码语言:javascript
复制
String args[] = {"this is id", "this is name"};

Arrays.asList(Book.class.getConstructors()).stream()
    .filter(c -> c.getParameterCount() == args.length).forEach(c -> {
      if (IntStream.range(0, c.getParameterCount()).allMatch(i -> {
        return Arrays.asList(c.getParameterTypes()[i].getDeclaredMethods()).stream()
            .filter(m -> m.getName().equals("valueOf")).anyMatch(m -> {
              try {
                m.invoke(null, args[i]);
                return true;
              } catch (Exception e) {
                return false;
              }
            });
      }))
        System.out.println("Matching Constructor: " + c);
    });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45174988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档