java 如果类型是原始类型或类型是对象,则检查反射
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14921406/
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
Check in reflection if type is primitive or type is object
提问by John Jerrby
Im using the following code to find class members in reflection that are primitive and some object ,my question is there is a way to identify if field is type primitive ,object ,class reference because i want to call to specific method according to the type. for example if field is primitive call to handlePrimitive if field type other type reference (in the example below SalesOrderItemPK primaryKey; )call to method handleClassReferance etc
我使用以下代码在反射中查找原始类和某个对象的类成员,我的问题是有一种方法可以识别字段是否为原始类型、对象、类引用,因为我想根据类型调用特定方法。例如,如果字段是对 handlePrimitive 的原始调用,如果字段类型为其他类型引用(在下面的示例中 SalesOrderItemPK primaryKey; )调用方法 handleClassReference 等
just of understanding i need to get the class and invistigate it and create data according to the member type...
只是为了理解我需要获取类并对其进行调查并根据成员类型创建数据...
for (Object clsObj : listClsObj) {
Field[] declaredFields = clsObj.getClass().getDeclaredFields();
numOfEntries = 1;
do {
Object newInstance = clsObj.getClass().newInstance();
for (Field field : declaredFields) {
// Get member name & types
Class<?> fieldType = field.getType();
Type genericType = field.getGenericType();
String fieldTypeName = fieldType.getName();
String memberName = field.getName();
if (genericType instanceof ParameterizedType) {
ParameterizedType pt = (ParameterizedType) genericType;
for (Type typeOfReferance : pt.getActualTypeArguments()) {
String classTypeName = typeOfReferance.toString();
String[] parts = classTypeName.split(" ");
memberReferance = parts[1];
here i want to call to specific method that can handle fields according to the data types
在这里我想调用可以根据数据类型处理字段的特定方法
public static SwitchInputType<?> switchInput(final String typeName, final String memberName, final int cnt) {
if (typeName.equals("java.lang.String")) {
return new SwitchInputType<String>(new String(memberName + " " + cnt));
} else if (typeName.equals("char")) {
return new SwitchInputType<Character>(new Character('a'));
the class for example should look like this and I need to know for primaryKey key to create an object.
例如,该类应该是这样的,我需要知道 primaryKey 键来创建一个对象。
@Entity
public class SalesOrderItem
{
@EmbeddedId
SalesOrderItemPK primaryKey;
private String ProductId;
private String Notes;
回答by Bozho
If you don't call .toString()
, but instead cast Type
to Class
, you get .isPrimitive()
如果您不调用.toString()
,而是强制转换Type
为Class
,则会得到.isPrimitive()