1

Let's say I have an object created from class:

public Class Cat {
  public Cat(String name) {
    this.name = name;
  }
}
Cat cat = new Cat("Just cat");

I create a Class-instance of my cat like this:

Class catClass = cat.getClass();

My question is, can I use that Class-object to create cats by doing something like this:

Cat newCat = catClass...something...("Another cat");

My problem is that I have a method accepting array of strings. This method needs to decide which object it has to construct using these strings as arguments. I tried to use getConstructor methods, but I can't seem to figure out how this works.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Voting to re-open because the linked question assumes you are working from a String class name. OP asked if you could create a new instance from an object, which doesn't require you to get the class name. This would work: cat.getClass().getConstructor( String.class ).newInstance( "Another cat" ) – Jesse Barnum Jan 11 '23 at 17:28
  • @JesseBarnum It shouldn't matter how you get the `Class` instance. The OP here already has one. The linked post explains how you can then use it to instantiate the class. – Sotirios Delimanolis Jan 11 '23 at 17:39

0 Answers0