This question already has an answer here:
I recently have encountered a strange error which I can't get my head around. I'm trying to instantiate derived classes of a base class through reflection, however the getConstructor method can't find the clearly existing constructor. In code:
package com.test;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
public class Test {
    abstract class Base {
        protected abstract String doWork(String param);
    }
    final class Derived extends Base {
        private String pattern;
        public Derived(String pattern) {
            this.pattern = pattern;
        }
        @Override
        public String doWork(String param) {
            return param.matches(pattern) ? param.toUpperCase() : param.toLowerCase();
        }
    }
    public static void main(String... args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Constructor<? extends Base> ctor = Derived.class.getConstructor(String.class);
        Base b = ctor.newInstance(".*");
        System.out.println(b.doWork("Hello World!"));
    }
}
Clearly shows my intention, I'd love to see "HELLO WORLD!" as an output however when I execute the application all I can see is:
Exception in thread "main" java.lang.NoSuchMethodException: com.test.Test$Derived.<init>(java.lang.String)
    at java.lang.Class.getConstructor0(Class.java:3074)
    at java.lang.Class.getConstructor(Class.java:1817)
    at com.test.Test.main(Test.java:25)
Now, it's clear that it picks up the Derived.class which clearly has an method with java.lang.String parameter however the exception still rises and tries to tell me there's no such thing.
Edit:
I should have known that someone will mark the question as duplicate without even looking at it in details. So just for you Mr. Sotirios Delimanolis, I know. Yeah, believe me, I know that you can pass the enclosing type as the first parameter to the constructor. Allow me to ask you something: Di you try it? Because I did. Do you think it works? No. Do you know why? Well I don't. So let's put things simple. If I move the Base and Derived classes outside of class Test, the upper program runs and gives the perfect output. I move them in, and not even your precious search works. Please first read the actual question and then mark it...
Aucun commentaire:
Enregistrer un commentaire