简体   繁体   English

如何在对象创建过程中避免构造函数调用?

[英]How to Avoid Constructor calling During Object Creation?

I want to avoid the constructor calling during object creation in java (either default constructor or user defined constructor) . 我想避免在java中创建对象期间的构造函数调用(默认构造函数或用户定义的构造函数)。 Is it possible to avoid constructor calling during object creation??? 在对象创建期间是否可以避免构造函数调用?

Thanks in advance...... 提前致谢......

Simply extract the intialization logic that you want to avoid into another method called init. 只需将要避免的初始化逻辑提取到另一个名为init的方法中。 You can not avoid calling exactly one constructor. 你无法避免只调用一个构造函数。

无论您使用何种模式或策略,在某些时候,如果要创建对象,您将需要调用构造函数。

Actually, its possible under some circumstances by using classes from the JVM implementation (which do not belong to the JRE API and are implemenation specific). 实际上,在某些情况下可以使用JVM实现中的类(它们不属于JRE API并且是特定于实现的)。

One example here http://www.javaspecialists.eu/archive/Issue175.html 这里有一个例子http://www.javaspecialists.eu/archive/Issue175.html

It should also be possible using sun.misc.Unsafe.allocateInstance() (Java7) 它也应该可以使用sun.misc.Unsafe.allocateInstance()(Java7)

Also, the constructor is apparently bypassed when using the clone()-method to create a copy of an object (and the class doesn't override clone to implement it different from the Object.clone() method). 此外,当使用clone()方法创建对象的副本时,显然绕过了构造函数(并且该类不会覆盖clone以实现它与Object.clone()方法不同)。

All of these possibilities come with strings attached and should be used carefully, if at all. 所有这些可能性都带有附加条件,如果有的话应该小心使用。

You can mock the constructors of a class. 您可以模拟类的构造函数。 They will still be called, but not executed. 它们仍将被调用,但不会被执行。 For example, the following JUnit+JMockit test does that: 例如,以下JUnit + JMockit测试执行此操作:

static class CodeUnderTest
{
    private final SomeDependency someDep = new SomeDependency(123, "abc");

    int doSomething(String s)
    {
        someDep.doSomethingElse(s);
        return someDep.getValue(); 
    }
}

static final class SomeDependency
{
    SomeDependency(int i, String s) { throw new RuntimeException("won't run"); }
    int getValue() { return -1; }
}

@Test
public void mockEntireClassIncludingItsConstructors()
{
    new NonStrictExpectations() {
        @Mocked SomeDependency mockDep;
        { mockDep.getValue(); result = 123; }
    };

    int result = new CodeUnderTest().doSomething("testing");

    assertEquals(123, result);
}

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

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