1

For many framework development, we need to instantiate class by reading qualified class names from a config file.

There are different introspection strategies, and dedicated libraries (like Objenesis) geared towards it.

However, for classes with no default constructor (overloaded) I believe no introspection works if we do not know the signature of the overloaded constructor. The non standard approach is to use sun.misc.Unsafe class to allocate. This is what I understand. Is that a correct understanding?

Then there's a problem with that, as super classes are not instantiated by using Unsafe. But I thought Unsafe is the closest to whatever C code 'new' operator invokes, at least a part of it.

So the question is, do we have Java ways of instantiating a object the way new operator does, by some form of introspection when the only information we have is the qualified name of the class (and of course that is present somewhere in the classpath!)

sutanu dalui
  • 663
  • 7
  • 25
  • 2
    You can always inspect the available constructors and see if you have any values you can pass to them. Dependency injection frameworks will do this for autowired constructor-injected objects - the assumption is that the objects you're creating mostly need other objects from your codebase, not "generic" parameters like strings; and that the DI container also manages these dependencies, and thus knows how to create them. – millimoose Nov 01 '13 at 12:21
  • Do you want to get an initialized object (a constructor invoked), or uninitialized one (no constructors and initializers invoked, fields have default (0 or null) values? – Alexei Kaigorodov Nov 01 '13 at 12:27
  • I want to have the superclass members initialized the same way. So is that "allocation" of an object on the heap, and instantiation of its members (which in turn might need allocation) are part of different strategies? @millimoose What you are saying is correct for a DI framework, since as you said "it is mostly objects from your codebase". However, I am kind of trying a generic, "object generator" for a project which takes external adaptor classes and did not want to restrict to a you-need-to-have-a-default-constructor defined. – sutanu dalui Nov 01 '13 at 12:43

2 Answers2

0

i'm not sure if i understand your question but usually in java if you know the class name you can simply write: classname myObject=new classname();

  • 1
    This question is related to runtime - in compile time he did not know type, so cannot write this. He has only string, that contain class name. – msangel Nov 01 '13 at 12:33
0

If all you have a is a class name, you can use Class.newInstance() but if it doesn't have a default constructor, you can use Unsafe.allocateInstance().

You can use reflection to find a constructor to call, but you don't know which one or what arguments to pass.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130