Java反射:获取字段类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22701751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:21:40  来源:igfitidea点击:

Java reflection: get class of field

javareflection

提问by Tucker

I have a method that requires something like Double.classas one of its inputs;

我有一个方法需要类似Double.class的输入之一;

e.g.

例如

someOutput = SomeObj.someMethod("parameter",Double.class);

I have another class that has a bunch of fields of different datatypes that I'd like to feed as input to this method in stead of explicitly writing Double.classof Integer.classetc etc.

我有了很多不同的数据类型的字段,我想作为输入养活这个方法取而代之的明确书面另一个类Double.classInteger.class等等等等。

I know this involves java reflection, but I'm not quite sure how to do what I want. I'm trying something like this but it isn't working:

我知道这涉及 Java 反射,但我不太确定如何做我想做的事。我正在尝试这样的事情,但它不起作用:

for(Field field : Class.forName(MyClassWithLotsOfFields.class.getCanonicalName()).getFields()){ 
   someOutput = SomeObj.someMethod("parameter",field.getClass());
  //Do more stuff here...
}   

but field.getClass()is not giving me the actual class of the field from MyClassWithLotsOfFieldsbut instead java.lang.reflect.Field

field.getClass()没有给我该领域的实际类,MyClassWithLotsOfFields而是java.lang.reflect.Field

any ideas for how to do what I want?

关于如何做我想做的任何想法?

采纳答案by Sotirios Delimanolis

You need Field#getType().

你需要Field#getType().

Returns a Classobject that identifies the declared type for the field represented by this Fieldobject.

返回一个Class对象,该对象标识此Field对象表示的字段的声明类型。

getClass()is a method inherited from Objectthat returns the type of the object itself.

getClass()是一个继承自的方法,Object它返回对象本身的类型。