简体   繁体   English

Java 反射:使用树形图中的参数创建实例,如 python

[英]Java reflection: create a instance using params from a treemap like python

I am a python dev, now i want to create a Java instance using params from a treemap just like create a python instance which params from a dict...i try to do it through java reflection.我是 python 开发人员,现在我想使用树形图中的参数创建一个 Java 实例,就像创建一个 python 实例,该实例的参数来自字典...我尝试通过 java 反射来实现。 but i can't find the solution.但我找不到解决办法。

anybody can give me a hand?谁能帮帮我? THX谢谢

Not sure I am following, but from what I understand - you are trying to create properties of the object on the fly.不确定我是否在关注,但据我了解 - 您正在尝试动态创建 object 的属性。

Well, that cannot be done in java, partially because the language is statically typed [unlike python].好吧,这不能在 java 中完成,部分原因是该语言是静态类型的[与 python 不同]。

In java, all fields of the object must be created at compile time .在java中,编译时必须创建object的所有字段 Reflection can help you to manipulate objects, but not to change their structure completely.反射可以帮助你操纵对象,但不能完全改变它们的结构。

A workaround could be to use a Map<String,Object> , and hold the properites there.一种解决方法是使用Map<String,Object>并在那里保存属性。 You will not need reflection for using this solution [which is a good thing, since reflection is both unsafe and tends to slow-down overall performance of the program].使用此解决方案不需要反射 [这是一件好事,因为反射既不安全又会降低程序的整体性能]。

Is this what you are looking for.这是你想要的。 Create a map to keep your classes.创建一个 map 来保留您的课程。

private static Map<String, Class<? extends MySuperClass>> classesMap = new HashMap<String, Class<? extends MySuperClass>>();

Put class objects in map将 class 个对象放入 map

static {
      classesMap.put("PERSON_CLASS", Person.class); 
      classesMap.put("ADDRESS_CLASS", Address.class);
}

Then a getInstance method that returns the instance of given class.然后是返回给定 class 实例的 getInstance 方法。

private static MySuperClass getInstance(String classNameConstant) throws Exception{
     Class<? extends MySuperClass> myClass = classesMap.get(classNameConstant);
     if(myClass!=null){
        return myClass.newInstance();
     }
     return null;
}

Hope this helps.希望这可以帮助。 Note: I don't know python.注意:我不知道 python。

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

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