Create Object Instance Without Invoking Constructor

Create object instance without invoking constructor?

I have not tried this, but there is a method called FormatterServices.GetUninitializedObject that is used during deserialization.

Remarks from MSDN says:

Because the new instance of the object
is initialized to zero and no
constructors are run, the object might
not represent a state that is regarded
as valid by that object.

How can I create an instance of class without invoking constructor of this class?

Here's a sure way to break your system, but at least it won't invoke the constructor. Use Unsafe#allocateInstance(Class)

import java.lang.reflect.Field;
import sun.misc.Unsafe;

public class Example {
private String value = "42";
public static void main(String[] args) throws Exception {
Example instance = (Example) unsafe.allocateInstance(Example.class);
System.out.println(instance.value);
}

static Unsafe unsafe;
static {
try {

Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
singleoneInstanceField.setAccessible(true);
unsafe = (Unsafe) singleoneInstanceField.get(null);
} catch (Exception e) {
e.printStackTrace();
}
}
}

which prints

null

indicating that the Example default constructor wasn't invoked.

Creating instance of type without default constructor in C# using reflection

I originally posted this answer here, but here is a reprint since this isn't the exact same question but has the same answer:

FormatterServices.GetUninitializedObject() will create an instance without calling a constructor. I found this class by using Reflector and digging through some of the core .Net serialization classes.

I tested it using the sample code below and it looks like it works great:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Runtime.Serialization;

namespace NoConstructorThingy
{
class Program
{
static void Main(string[] args)
{
MyClass myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass)); //does not call ctor
myClass.One = 1;
Console.WriteLine(myClass.One); //write "1"
Console.ReadKey();
}
}

public class MyClass
{
public MyClass()
{
Console.WriteLine("MyClass ctor called.");
}

public int One
{
get;
set;
}
}
}

creating object instance without invoking initializer

JVM specification prohibits creation of objects without calling proper constructor.
However, there are two tricky ways of doing this.
Both of them are specific to OpenJDK / Oracle JDK and are not guaranteed to work on all Java implementations.

  1. Call sun.misc.Unsafe.allocateInstance() internal API to instantiate a class without calling a constructor.
  2. When generating a class in run-time, inherit your class from sun.reflect.MagicAccessorImpl. JVM will skip bytecode verification for such class thus allowing to have NEW bytecode without proper INVOKESPECIAL.

Both techniques are used in our custom serialization engine which can be found at https://github.com/odnoklassniki/one-nio/blob/master/src/one/nio/serial/

How can I create an object of a class with no constructor, C#

You can't instantiate that class without reflection, which is a bit hacky (depending on an internal interface is suboptimal because API maintainers typically don't care about keeping internal bits backwards compatible.

The doc tag gives you an important clue:
"This API is accessed via the IpfsClient.FileSystem property. "

Is it possible to create an instance of an object in Java without calling the constructor?

Actually, yes, it is possible to bypass the constructor when you instantiate an object, if you use objenesis to instantiate the object for you. It does bytecode manipulations to achieve this.

Deserializing an object will also bypass the constructor.

It isn't possible to do this using reflection.

C# Reflection: Create object from assembly without invoking constructorinfo

Found some clues from:

How to identify each parameter type in a C# method?

Where @JaredPar saying the following:
To get the actual Type of the parameter use the ParameterType on the ParameterInfo value. With that value there are several ways you can use it to identify the type. The easiest is with a direct comparison to a known type.

So in my case I need to Identify the type of the parameterType and create a new instance of that type before I send it to the constructor.

Because I only care of the type of the object, I could resolve it by

var fixture = new Fixture(); //Ploeh.AutoFixture
var obj = new SpecimenContext(fixture).Resolve(asmtype); //Ploeh.AutoFixture.Kernel.SpecimenContext

So after getting the assemblytype I just create a fixture and a specimentContext with fixture and then resolve the asmType.

This object will be of the corresponding type.

So Final result:

   foreach (var asmtype in assemblyTypes)
{
var fixture = new Fixture();
var obj = new SpecimenContext(fixture).Resolve(asmtype);

_handler.Error(new Login { BrandId = _brandId }, new Domain.Entities.Customer { CustomerId = It.IsAny<Guid>() }, (Exception) obj);

if (obj is InvalidCredentialsException)
_loginRepository.Verify(v => v.ZZZ(It.IsAny<Guid>(), It.IsAny<int>()), Times.Once);
else
_loginRepository.Verify(v => v.ZZZ(It.IsAny<Guid>(), It.IsAny<int>()), Times.Never);
}

Instantiating objects without calling the constructor in C++

5 is an example of C++'s most vexing parse.

Dog dog();

This declares a function named dog that accepts no parameters and returns a Dog. To avoid the most vexing parse (and if you are using C++11), you can do:

Dog dog{};

And semantically (at least until C++17), Dog dog = Dog(); will first create a temporary object (Dog()), and then move construct (or copy construct, if Dog class has no move constructor) a named object (dog) from it. Although compilers might optimize the move away, this statement does have different semantics from the rest.

If I remember correctly, since C++17, P0135r0 will change the semantics of Dog dog = Dog(); so that it has the same meaning as Dog dog;.

EDIT: As pointed out by @LightnessRacesinOrbit in the comments, Dog dog(); is vexing, but not quite the most vexing parse. Dog dog(Dog()); is true most vexing parse. Dog dog(); is just a, well, plain declaration, I guess.



Related Topics



Leave a reply



Submit