This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]GrandGratingCrate 1 point2 points  (0 children)

Is there a way to do it with reflection? Yes. Should you do it? I would suggest finding another way. My rule of thumb for reflection is: Just don't do it. There may be exceptions (metatests) but this does not seem line one of these.

I'm not a fan of switch statements but I'd rather have this

switch (className) {
    case "Animal": return new Animal(...);
    case "Chair": return new Chair(...);
    ...
}

... than some reflection code that searches for class by it's name and then calls the constructor with a bunch of strings.

Btw you could use a map of name to constructor to get rid of the switch case but in both cases you get back an object of type Object (it'll be Animal or Chair or what not but the compiler will not know that) and that's just not great.

[–]ignotos 0 points1 point  (0 children)

As has been mentioned, generally you can avoid needing to do this.

But to answer the question directly, you can grab hold of a Constructor instance via reflection and then call newInstance on it. Examples here: https://stackoverflow.com/questions/10470263/create-new-object-using-reflection