简体   繁体   English

Java Reflection用于创建新对象

[英]Java Reflection for creating new objects

Is there a way to create primitive data type variables use Java Reflection? 有没有一种方法可以使用Java Reflection创建原始数据类型变量?

For example, 例如,

public Object createObj(String type, String value){
  if(type.compareTo("char") == 0)
    //return a char
  else if(type.compareTo("int") == 0)
    //return an int
  ....
}

The common idiom I see here is to use Class.forName() . 我在这里看到的常见用法是使用Class.forName()

public static Object makeNew(String type) throws Exception {
    Class clazz = Class.forName(type);
    return clazz.newInstance();
}

For int , char you have to use the names of their respective class-types, you can't actually make a primitive. 对于intchar您必须使用它们各自的类类型的名称,实际上不能创建基元。 "java.lang.Integer", "java.lang.Character", etc. respectively. 分别是“ java.lang.Integer”,“ java.lang.Character”等。 You'll need to check those specially if you want to pass in "int", "char", etc. 如果要传递“ int”,“ char”等,则需要特别检查。

Adding a "value" as a string is much harder. 添加“值”作为字符串要困难得多。 Most classes will not have a way of changing a string into an initial state. 大多数类都无法将字符串更改为初始状态。 You'll definitely have to special case the primitives to provide an initial value. 您绝对必须对原语进行特殊处理以提供初始值。 Overall, I think this is not a great way to approach whatever problem you are tying to solve. 总体而言,我认为这不是解决您要解决的任何问题的好方法。


So you mention in your comment about using setter methods. 因此,您在评论中提到了使用setter方法。 One problem is how do you determine which setter do you call? 一个问题是如何确定要呼叫哪个二传手? If you pass a parameter of "10", for a JButton , is that the setAlignmentX , setAlignmentY , or the setText method? 如果为JButton传递参数“ 10”,则是setAlignmentXsetAlignmentY还是setText方法?

At this point you have to go whole hog on it. 此时,您必须全力以赴。

<class>
  <name>javax.swing.JButton</name>
  <set><method>setAlignmentX</method><value>10</value></set>
</class>

Now you have the problem that some setters take other classes as parameters. 现在,您遇到了一些设置器将其他类用作参数的问题。 And some classes are immutable ( Integer and Character are), they have no setters at all, you'll have to call a ctor. 而且有些类是不可变的( IntegerCharacter是),它们根本没有设置器,您必须调用ctor。

You're basically getting into serialization here (which is a very hard problem). 您基本上是在这里进行序列化的(这是一个非常困难的问题)。 Take a look at XmlEncoder and XmlDecoder , they do something close to what you want. 看一下XmlEncoderXmlDecoder ,它们所做的事情接近您想要的。 https://docs.oracle.com/javase/8/docs/api/java/beans/XMLEncoder.html https://docs.oracle.com/javase/8/docs/api/java/beans/XMLEncoder.html

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

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