1

How do I instantiate an object using the Class class?

I would like to pass a Class object to a function and have that function return a new object of the class I pass in.

I will be doing casting after I get the object back. Also, are there any suggestions on design patterns for this sort of thing?

Here is some example pseudo code that shows what I want to do:

Class Animal {
    String name;
}

Class Cat extends Animal {
    boolean hasTail;
}

MAIN:

Class myClass = Cat.class;
Animal createAnimal(myClass) {
    return new myClass;
}

Edit:

Also, is there a way to cast within my function before returning the new instance or am I stuck with the default Object type?

return (myClass)myClass.newInstance();
4
  • What you want to achieve eerily resembles the Factory pattern. Check this thing out: allapplabs.com/java_design_patterns/factory_pattern.htm and annotate your question with the homework tag Commented Jan 7, 2012 at 14:11
  • @Perception No. But I'll take any resources you post and read up on it. Commented Jan 7, 2012 at 14:11
  • Fair enough. Here is the Javadoc for java.lang.Class. Pay particular attention to the newInstance method: docs.oracle.com/javase/6/docs/api/java/lang/Class.html Commented Jan 7, 2012 at 14:13
  • You can check which instance of myClass belongs to by if(myClass instanceOf Cat) {return new Cat()} Commented Jan 7, 2012 at 14:21

3 Answers 3

6

I suspect you want Class.newInstance(). Note that you'd call it with Cat.class, not Cat.getClass().

Note that newInstance() will always try to call a parameterless constructor - if you need to pass any arguments, use getConstructors() to find the constructors declared by that class, then invoke the appropriate one.

Sign up to request clarification or add additional context in comments.

5 Comments

this will work only in the case that his Class has a no-args constructor (which seems to be the case currently), so +1
Say there were args... do I just put the parameters in the call? Ex. Class.newInstance(arg1,arg2)?
@Matthew: No, you call getConstructors(), find the appropriate one, then call constructor.newInstance(arg1, arg2, ...)
@baba is that for the single line function declaration and open brace? I had them on separate lines before. Mine wasn't kosher according to Java best practices am I right? Or is that just personal preference?
People would disagree, but I hear in C# separate lines are standard. It depends on the company and team you work in, you should fit in. I personally write code like 'an Egyptian'. Both methods are OK, but Oracle(Sun) prefer the Egyptian style: oracle.com/technetwork/java/codeconventions-141999.html#216 Since you are using other people's code as well, which is mostly written in the same style as Sun's, it is a good idea for your code to also conform to those standards.
2

I will be doing casting after I get the object back.

Also, is there a way to cast within my function before returning the new instance or am I stuck with the default Object type?

You don't need to do casting if you take advantage of generics. Generics are described in relatively introductory detail here

Here is a java example derived from your psuedo code using generics and reflection:

public class ReflectionNewInstanceTest {

    static class Animal {
        String name;
    }

    static class Cat extends Animal { 
        boolean hasTail = true;
    }

    public static void main(String[] args) throws Exception {
        Animal a = createAnimal(Cat.class);
    }


    static <T extends Animal> T createAnimal(Class<T> clazz) throws Exception {
        return clazz.newInstance();
    }

}

As for patterns, any of the typical creational patterns should be looked at when you want to abstract away the creation of objects. The simplest is probably just using a factory method. The example I have above is just a general purpose factory method that doesn't really gain you much. Here is a pretty short list of patterns you should look up:

  • Abstract factory pattern
  • Factory method pattern
  • Builder pattern
  • Prototype pattern

Comments

1

You are probably looking for the getConstructor() and the newInstance() methods in Class, Constructor classes respectively.

If your constructor is guaranteed to have no arguments, you might also shorthand it and use newInstance() [in Class]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.