奇怪的错误在java反射(处理) [英] strange error in java reflection (processing)

查看:154
本文介绍了奇怪的错误在java反射(处理)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从我上一个问题的答案:如何以最好的方式从类对象创建一个实例



我试图做他建议的,但我不'



  import java.lang.reflect。*; 

class Foo {
public< T> T create(float x,float y,Class< T> myClass)
throws Exception {
构造函数< 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);
}

例外情况



java.lang.NoSuchMethodException:sketch_140319d $ 1Dog。< init>(float,float)

解决方案

正如我刚刚评论你的另一个问题,如果 Dog 是一个非静态内部类 sketch_140319 ,错误消息建议。我想你从你的问题中删除了 sketch_140319 类 - 我不知道你为什么这样做,当这是什么问题。



您需要 使 Dog static,添加 sketch_140319.class 作为 getConstructor 的第一个参数,以及 sketch_140319 newInstance 的第一个参数。


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)

解决方案

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.

这篇关于奇怪的错误在java反射(处理)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆