简体   繁体   中英

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

One example here http://www.javaspecialists.eu/archive/Issue175.html

It should also be possible using 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).

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:

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);
}

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