0

I have a class called BankAccount with 2 constructors, one with no argument and the second take an int as a parameter:

public final class BankAccount {

    private int balance;
    public String name;

    public BankAccount() {

    }

    public BankAccount(int startBalance) {
        balance = startBalance;
    }
}

so when I try to create an object using the constructor with the integer param like this :

    try {
        BankAccount account = BankAccount.class.getConstructor(Integer.class).newInstance(100);
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

I get the exception of NosuchMethodException.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
R0b0t0
  • 390
  • 6
  • 20
  • 1
    Why don't you use `new BankAccount(100);` ? – cdaiga Nov 20 '17 at 16:46
  • Autoboxing may not work here. You don't have a constructor with an Integer. Either convert the constructor to an Integer or call the getConstructor with an int. – older coder Nov 20 '17 at 16:46
  • 1
    Your constructor takes `int` not `Integer`, so instead of `Integer.class` use `int.class` or `Integer.TYPE`. – Pshemo Nov 20 '17 at 16:47

0 Answers0