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
Java reflection: get class of field
提问by Tucker
I have a method that requires something like Double.class
as 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.class
of Integer.class
etc etc.
我有了很多不同的数据类型的字段,我想作为输入养活这个方法取而代之的明确书面另一个类Double.class
的Integer.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 MyClassWithLotsOfFields
but 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
Class
object that identifies the declared type for the field represented by thisField
object.
返回一个
Class
对象,该对象标识此Field
对象表示的字段的声明类型。
getClass()
is a method inherited from Object
that returns the type of the object itself.
getClass()
是一个继承自的方法,Object
它返回对象本身的类型。