English 中文(简体)
在java,能否在没有使用反思的无ar建筑者的情况下制造班级空白?
原标题:Is it possible in java to create blank instance of class without no-arg constructor using reflection?

I have a class which has not default constructor. And I need a way to get blank instance of this class. blank means that after instantiation all class fields should has default values like null, 0 etc.

我 asking问,因为我需要能够把大树的物体连成序列/代谢。 我无法获得这些物体的种类和种类的源头,既没有违约的构造,也无法执行序列。 试图将这种结构序列化的做法可能并不好,但另一种办法是将其转换成更易于序列的。

最佳回答

有了标准思考,就没有,但有一个能够供你使用的图书馆:objenesis

它专门设计在不设违约建筑商的情况下即时课,并用于其他序列化图书馆,如xstream

注:在这些情况下,可能不会传唤施工人(但假定这是你想要的)。

问题回答

提供班级作为可变的芯片:

ReflectionFactory rf = ReflectionFactory.getReflectionFactory();
Constructor objDef = parent.getDeclaredConstructor();
Constructor intConstr = rf.newConstructorForSerialization(clazz, objDef);
clazz.cast(intConstr.newInstance());

http://www.javaspecialists.eu/archive/Issue175.html。

你的解决方案将是证书考试和测验。

如果需要一个便携式解决方案,则使用第三边图书馆<>。

对Sun s JVM v1.5来说,你可以这样做:

    final Class<?> myClass = MyClass.class;
    final ReflectionFactory reflection = ReflectionFactory.getReflectionFactory();
    final Constructor<Object> constructor = 
        reflection.newConstructorForSerialization(
            myClass, Object.class.getDeclaredConstructor(new Class[0]));
    final Object o = constructor.newInstance(new Object[0]);

    System.out.print(o.getClass());

XStream的相关班级是:

  • com.thoughtworks.xstream.converters.reflection.PureJavaReflectionProvider
  • com.thoughtworks.xstream.core.JVM;

我认为,唯一的解决办法是使用一个密码操纵图书馆,例如javassist,添加一个违约构造。

如果贵阶层没有其他建筑商,则汇编者将为你们创造一席。 你们也许会有一个无ar的建筑商,而不会实现。

如果你不写造物,你包括:even one Constructionor,提出论据,则编辑者不会给你。 反省得到了帮助:如果你试图找到一个无ar的建筑家,那就会出现什么?

它像你一样使用 Java物体序列化,使用java.lang。 诚然,但这不是你的唯一选择。 你们也可以使用XML,或JSON,或原型缓冲,或任何其他方便的议定书。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签