简体   繁体   中英

Java Reflection for creating new objects

Is there a way to create primitive data type variables use 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() .

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. "java.lang.Integer", "java.lang.Character", etc. respectively. You'll need to check those specially if you want to pass in "int", "char", etc.

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. 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?

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.

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. https://docs.oracle.com/javase/8/docs/api/java/beans/XMLEncoder.html

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