你可以使用Java反射找到的类型进行类型转换吗?

huangapple go评论102阅读模式
英文:

Can I perform type conversion using the type found through Java reflection?

问题

我可以使用Java反射找到的类型进行类型转换吗?

public class Dto {
    private String name;
    private int age;

    public Dto(){}
}

它具有两个不同类型的字段。

@Test
public void reflectionsTest3() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
    Class<Dto> dtoClass = Dto.class;
    Dto dto = dtoClass.getDeclaredConstructor().newInstance();
    Field[] fields = dtoClass.getDeclaredFields();
    Arrays.stream(fields).forEach(field -> {
        field.setAccessible(true); 
        Type T = field.getType();
        field.set(dto, (T) "1");
    });
}

它出现错误
我想要检测类型并为其赋予与类型匹配的值。
我如何使用这些类型?

英文:

Can I perform type conversion using the type found through Java reflection?

public class Dto {
    private String name;
    private int age;

    public Dto(){}
}

It has two fields of different types.

    @Test
    public void reflectionsTest3() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class&lt;Dto&gt; dtoClass = Dto.class;
        Dto dto = dtoClass.getDeclaredConstructor().newInstance();
        Field[] fields = dtoClass.getDeclaredFields();
        Arrays.stream(fields).forEach(field -&gt; {
            field.setAccessible(true); 
            Type T = field.getType();
            field.set(dto,(T) &quot;1&quot;);
        });
    }

it make error
I want to detect the type and give it a value that matches the type.
How can I use types?

答案1

得分: 0

你可以使用 Map 来保存字段类和该类的值供应商之间的映射。

public class RandomStuff {

  public static void main(String[] args) throws Exception {
    //...
    Map<Class<?>, Supplier<?>> map = new HashMap<>();
    map.put(String.class, () -> "some string");
    map.put(int.class, () -> 29);
    Arrays.stream(fields).forEach(field -> {
      field.setAccessible(true);
      Class<?> clazz = field.getType();
      try {
        Supplier<?> valueSupplier = map.get(clazz);
        if (valueSupplier == null) {
          // 处理无供应商的类型
        }
        field.set(dto, valueSupplier.get());
      } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
      }
    });
  }
}
英文:

You can use Map to hold mappings between field class and supplier of value for this class.

public class RandomStuff {

  public static void main(String[] args) throws Exception {
    //...
    Map&lt;Class&lt;?&gt;, Supplier&lt;?&gt;&gt; map = new HashMap&lt;&gt;();
    map.put(String.class, () -&gt; &quot;some string&quot;);
    map.put(int.class, () -&gt; 29);
    Arrays.stream(fields).forEach(field -&gt; {
      field.setAccessible(true);
      Class&lt;?&gt; clazz = field.getType();
      try {
        Supplier&lt;?&gt; valueSupplier = map.get(clazz);
        if (valueSupplier == null) {
          // handle no supplier for type
        }
        field.set(dto, valueSupplier.get());
      } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
      }
    });
  }
}

答案2

得分: 0

是的,您可以使用Java反射来执行类型转换。一旦通过反射获取了表示所需类型的Class对象,您可以使用Java中提供的各种方法来执行类型转换或强制转换。

您提供的代码尝试使用Java反射将Dto对象中每个字段的值设置为字符串值"1"。但是,这将导致错误,因为您尝试从String转换为T类型,其中T表示通过反射获取的字段的类型。

问题在于从field.getType()获取的类型T是一个Type对象,而不是可用于强制转换的具体类类型。Type接口不提供直接的对象转换方式。

您可以尝试更改代码如下并进行尝试。

        Class<?> fieldType = field.getType();
        if (fieldType.isAssignableFrom(String.class)) {
            try {
                field.set(dto, "1");
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

在此代码片段中,我们将fieldType作为Class对象获取,而不是Type。然后,我们检查fieldType是否可分配给String.class。如果可以,我们继续使用field.set(dto, "1")将字段的值设置为"1"。

我们对String进行类型检查,因为您试图将字段值设置为"1"。

英文:

Yes, you can perform type conversion using the type found through Java reflection. Once you have obtained the Class object representing the desired type through reflection, you can use various methods available in Java to perform type conversion or casting.

The code you provided attempts to set the value of each field in the Dto object to the string value "1" using Java reflection. However, it will result in an error because you are trying to perform a type cast from String to T, where T represents the type of the field obtained through reflection.

The problem is that the type T obtained from field.getType() is a Type object and not a concrete class type that can be used for casting. The Type interface does not provide a direct way to cast objects.

You can try changing the code as such any give it a try.

        Class&lt;?&gt; fieldType = field.getType();
        if (fieldType.isAssignableFrom(String.class)) {
            try {
                field.set(dto, &quot;1&quot;);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

This snippet, we obtain the fieldType as a Class<?> object instead of Type. Then, we check if the fieldType is assignable from String.class. If it is, we proceed to set the value of the field to "1" using field.set(dto, "1").

We do the type check for String since you are trying to set the field value as "1".

huangapple
  • 本文由 发表于 2023年5月29日 17:57:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356356.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定