简体   繁体   English

从Java反射创建对象而无需了解构造函数参数

[英]Creating a object from java reflection without knowing the constructor parameters

I am trying to create a collecion of objects using reflection. 我正在尝试使用反射创建对象集合。 I have the class name. 我有班级名称。 But at compile time have no idea about the constructor. 但是在编译时对构造函数一无所知。 I used this tutorial. 我使用了本教程。

import java.lang.reflect.*;

  public class constructor2 {
      public constructor2()
      {
      }

  public constructor2(int a, int b)
  {
     System.out.println(
       "a = " + a + " b = " + b);
  }

  public static void main(String args[])
  {
     try {
       Class cls = Class.forName("constructor2");
       Class partypes[] = new Class[2];
        partypes[0] = Integer.TYPE;
        partypes[1] = Integer.TYPE;
        Constructor ct 
          = cls.getConstructor(partypes);
        Object arglist[] = new Object[2];
        arglist[0] = new Integer(37);
        arglist[1] = new Integer(47);
        Object retobj = ct.newInstance(arglist);
     }
     catch (Throwable e) {
        System.err.println(e);
     }
  }

} }

Now let's say I don't know abut the parameters of the constructors. 现在说我不知道​​构造函数的参数。 (Whether it's a default constructor or two integers). (无论是默认构造函数还是两个整数)。 The costructor parameters can change from class to class. 构造函数参数可以在类之间更改。 I have no idea about the Constructor2 class. 我不知道关于Constructor2类。 But I have the className. 但是我有className。 So I cant create the "argList" as above. 因此,我无法如上所述创建“ argList”。 Any idea how I can create a object from constructors then. 任何想法然后我可以如何从构造函数创建对象。

I did as follows 我做了如下

Constructor[] brickConstructorsArray = brickClass.getConstructors();
            for (Constructor constructor : brickConstructorsArray) {
                Class[] constructorParams = constructor.getParameterTypes();

                Object argList[] = new Object[constructorParams.length];
                int index = 0;
                for (Class cls : constructorParams) {

                    if (cls.equals(Sprite.class)) {
                        Object spriteOb = foundSprite;
                        argList[index] = spriteOb;
                    } else if (cls.equals(double.class)) {
                        Object dblObj = new Double(0.0);
                        argList[index] = dblObj;
                    }

                    index++;
                }
                brickObject = (Brick) constructor.newInstance(argList);

            }

This would work for costrcutors which will have Sprite or double parameters. 这将适用于具有Sprite或double参数的Costrcutor。 To include other possibilities I'd have to create a loooong if else chain. 为了包括其他可能性,我必须创建一个loooong if else链。 Need help. 需要帮忙。

Do you really not care what values you're going to pass? 您真的不在乎要传递什么价值吗? You could have a map from each primitive class to a default value of its wrapper type: 您可以从每个基本类到其包装器类型的默认值都有一个映射:

// You can make this a static member somewhere
Map<Class<?>, Object> primitiveValues = new HashMap<Class<?>, Object>();
primitiveValues.put(char.class, '\0');
// etc

... and just use null for any non-primitive type. ...并将null用作任何非基本类型。 So: 所以:

Constructor[] brickConstructorsArray = brickClass.getConstructors();
for (Constructor constructor : brickConstructorsArray) {
    Class[] constructorParams = constructor.getParameterTypes();

    Object argList[] = new Object[constructorParams.length];

    // When you need the index, there's no point in using the enhanced
    // for loop.
    for (int i = 0; i < constructorParams.length; i++) {
        // Fetching the value for any non-primitive type will 
        // give null, which is what we were going to use anyway.
        argList[i] = primitiveValues.get(constructorParams[i]);
    }

    brickObject = (Brick) constructor.newInstance(argList);
}

Of course I'd expect this to fail quite often. 当然,我希望这会经常失败。 After all, if you don't know anything about the constructor you're calling, you have no idea what arguments are going to be valid. 毕竟,如果您对所调用的构造函数一无所知,则不知道什么参数是有效的。

Is this really something you're expecting to find useful? 真是你希望找到有用吗?

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

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