Create an instance of a class from a string
Take a look at the Activator.CreateInstance method.
Create object instance of a class from its name in string variable
Having the class name in string is not enough to be able to create its instance.
As a matter of fact you will need full namespace including class name to create an object.
Assuming you have the following:
string className = "MyClass";
string namespaceName = "MyNamespace.MyInternalNamespace";
Than you you can create an instance of that class, the object of class MyNamespace.MyInternalNamespace.MyClass
using either of the following techniques:
var myObj = Activator.CreateInstance(namespaceName, className);
or this:
var myObj = Activator.CreateInstance(Type.GetType(namespaceName + "." + className));
Hope this helps, please let me know if not.
How to create class instance by string name
Class[] types = {Integer.TYPE};
Constructor constructor = myClass.getConstructor(types);
This looks up a constructor that takes one int
or Integer
, not an array of int
s.
If you want to lookup the constructor that takes an int[]
, then pass the correct arguments:
Class[] types = { int[].class };
Constructor constructor = myClass.getConstructor(types);
Create class object instance named from string?
Generally speaking, dynamically created variable names are a bad idea. Instead, you should create a dictionary where the name is the key and the instance is the value
In your case it would look something like this:
objects = {}
...
object_name = line.split()[2]
objects[object_name] = vrf()
Then you can access it this way for your example:
objects["TESTER"]
will give you the corresponding vrf instance.
Instantiate object from class name as string
You can create an instance of a class and run its methods without ever having to import the class in your code using reflection:
Class clazz = Class.forName("com.whatever.MyClass");
Object instance = clazz.newInstance(); // or use the given instance
clazz.getMethod("myMethod").invoke(instance);
Is there a way to instantiate a class by name in Java?
Two ways:
Method 1 - only for classes having a no-arg constructor
If your class has a no-arg constructor, you can get a Class
object using Class.forName()
and use the newInstance()
method to create an instance (though beware that this method is often considered evil because it can defeat Java's checked exceptions).
For example:
Class<?> clazz = Class.forName("java.util.Date");
Object date = clazz.newInstance();
Method 2
An alternative safer approach which also works if the class doesn't have any no-arg constructors is to query your class object to get its Constructor
object and call a newInstance()
method on this object:
Class<?> clazz = Class.forName("com.foo.MyClass");
Constructor<?> constructor = clazz.getConstructor(String.class, Integer.class);
Object instance = constructor.newInstance("stringparam", 42);
Both methods are known as reflection. You will typically have to catch the various exceptions which can occur, including things like:
- the JVM can't find or can't load your class
- the class you're trying to instantiate doesn't have the right sort of constructors
- the constructor itself threw an exception
- the constructor you're trying to invoke isn't public
- a security manager has been installed and is preventing reflection from occurring
Creating PHP class instance with a string
Yes, you can!
$str = 'One';
$class = 'Class'.$str;
$object = new $class();
When using namespaces, supply the fully qualified name:
$class = '\Foo\Bar\MyClass';
$instance = new $class();
Other cool stuff you can do in php are:
Variable variables:
$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123
And variable functions & methods.
$func = 'my_function';
$func('param1'); // calls my_function('param1');
$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method.
Related Topics
How to Convert Date Format to Dd-Mm-Yyyy in C#
Unity3D Ui, Calculation for Position Dragging an Item
Add Timer to a Windows Forms Application
Why Do I Get "System.Data.Datarowview" Instead of Real Values in My Winforms Listbox
How to Programmatically Select an Item in a Wpf Treeview
Does .Net's Httpwebresponse Uncompress Automatically Gziped and Deflated Responses
The Data Source Does Not Support Server-Side Data Paging
Does Filestreamresult Close Stream
Error: Must Create Dependencysource on Same Thread as the Dependencyobject Even by Using Dispatcher
How to Detect Which .Net Runtime Is Being Used (Ms VS. Mono)
Regex Word Boundary Expressions
Why Does the Linq Cast<> Helper Not Work with the Implicit Cast Operator
What's Difference Between Environment.Exit() and Application.Shutdown()
What Happens While Waiting on a Task's Result
Ssis Task for Inconsistent Column Count Import
How to Disable Cascade Delete for Link Tables in Ef Code-First