Create new instance of passed Class.class argument

Let's say that I have a function that has the purpose of creating a new instance of any specified class, and then returning it. Perhaps something like this:

public static <T> Class<T> forgeClass(Class<T> classReference) {

    return new classReference.getClass();

}

Usage (with Employee class):

Employee foo = forgeClass(Employee.class); // new Employee instance

How can I achieve this?

Answers


The key is to use Class.newInstance;

public static <T> T forge(final Class<T> type)
    throws InstantiationException, IllegalAccessException {
  return type.newInstance();
}

Use as follows...

final Employee employee = forge(Employee.class);

In case you want to use a more complex initialization routine, e.g. Employee(String name), you should use Class.getConstructor, followed by Constructor.newInstance.

final Constructor ctor = Employee.class.getConstructor(String.class);
final Employee employee = ctor.newInstance("Steve");

Need Your Help

Passing GET variables into PHP to instantiate classes and call functions

php html function variables get

I successfully instantiated the object class but I can't figure out how to call a function.

BorderLayout correct syntax

java swing syntax border-layout

as far as i know the syntax of the add method is

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.