-1
import java.lang.reflect.*;

public class Test {

    public Test(int x) {
        System.out.println("Constuctor called! x = " + x);
    }

    public static void main(String[] args) throws Exception {
        Class<? extends Thing> clazz = Stuff.class;
        Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
        Thing instance = ctor.newInstance(5);           
    }
}

public class Thing{
  public Thing(int x){
    System.out.println("Constructor! x = " + x);
  }
}

public class Stuff extends Thing{
  public Stuff(int x){
    super(x*2);
  }
}

The code above works as expected.

import java.lang.reflect.*;

public class Test {

    public Test(int x) {
        System.out.println("Constuctor called! x = " + x);
    }

  static void Create(){
    Class<? extends Thing> clazz = Stuff.class;
    Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
    Thing instance = ctor.newInstance(5);     
  }


    public static void main(String[] args) throws Exception {
      Create();      
    }
}

public class Thing{
  public Thing(int x){
    System.out.println("Constructor! x = " + x);
  }
}

public class Stuff extends Thing{
  public Stuff(int x){
    super(x*2);
  }
}

This code does not. I get these errors:

/tmp/java_tXpJ5P/Test.java:11: error: unreported exception NoSuchMethodException; must be caught or declared to be thrown
        Constructor<? extends Thing> ctor = clazz.getConstructor(int.class);
                                                                ^
/tmp/java_tXpJ5P/Test.java:12: error: unreported exception InstantiationException; must be caught or declared to be thrown
        Thing instance = ctor.newInstance(5);     
                                         ^
2 errors

Am I missing something very obvious or something very arcane here? It just seems bizarre. This is a simplification of code in a much more complex project that is structured slightly differently (and I'm passing Class as an argument) but produces the same errors.

Thanks very much

  • 1
    Well, the exception meesage just tells it – `newInstance()` declares that it *may* throw a `NoSuchMethodException`. This is a *checked exception*, so the method calling it should either handle it with try/catch or declare it to be thrown. In your first code snippet, `main` declares a possible `Exception` to be thrown, satisfying the compiler. However, your `Create` method does not have a throws clause while it should. `Create()` should be `create() throws NoSuchMethodException, InstantiationException`. – MC Emperor May 02 '20 at 18:17

1 Answers1

1

Your main method throws Exception, which means whatever happens there it will be throw. Your new code has no throws Exception and your code is throwing 2 potential Exceptions (InstantiationException and NoSuchMethodException). You have to take care of them either throwing (as the main method) or wrapping it on a try-catch statement.

Lucas Campos
  • 1,860
  • 11
  • 17