问题
From an answer in this my previous question: how to create in best way an instance from the class object
I'm trying to do what he suggests but I don't know how to fix the error.
Code:
import java.lang.reflect.*;
class Foo {
public <T> T create(float x, float y, Class<T> myClass)
throws Exception {
Constructor<T> toCall = myClass.getConstructor(float.class, float.class);
return toCall.newInstance(x, y);
}
}
class Dog {
public Dog(float x, float y) {
print(x);
print(y);
}
}
Foo foo = new Foo();
try {
foo.create(10.0f, 10.0f, Dog.class);
} catch (Exception e) {
print(e);
}
Exception:
java.lang.NoSuchMethodException: sketch_140319d$1Dog.<init>(float, float)
回答1:
As I have just commented on your other question, this won't work if Dog is a non-static inner class of sketch_140319, which the error message suggests. I guess you stripped out the sketch_140319 class from your question - I don't know why you did that, when this is what the problem was.
You need to either make Dog static, or add sketch_140319.class as the first argument to getConstructor and an instance of sketch_140319 as the first argument to newInstance.
回答2:
you can't call
foo.create(10.0, 10.0, Dog.class);
because 10.0 is a double, not a float
to call it like a float, do
foo.create(10.0f, 10.0f, Dog.class);
Update: my code is
class Dog {
public Dog(float x, float y) {
print(x);
print(y);
}
private void print(float x) {
System.out.println(x);
}
}
and
import java.lang.reflect.Constructor;
class Foo {
public <T> T create(float x, float y, Class<T> myClass)
throws Exception {
Constructor<T> toCall = myClass.getConstructor(float.class, float.class);
return toCall.newInstance(x, y);
}
}
and
public class SomeOtherClass {
/**
* @param args
*/
public static void main(String[] args) {
Foo foo = new Foo();
try {
foo.create(10.0f, 10.0f, Dog.class);
} catch (Exception e) {
e.printStackTrace();
}
}
}
and it returned
10.0
10.0
来源:https://stackoverflow.com/questions/22495012/strange-error-in-java-reflection-processing