不兼容的类型找到java.lang.class< capture< ?>>,所需字符、字节、短字符、int

eh57zj3b  于 2021-08-25  发布在  Java
关注(0)|答案(0)|浏览(260)

我正在编写一个模拟类,它可以使用反射(我没有找到反射)根据其类型设置字段值。然后我意识到一个有趣的现象:

  1. public void play(Class c)
  2. throws NoSuchMethodException, IllegalAccessException,
  3. InvocationTargetException, InstantiationException {
  4. Constructor declaredConstructor = c.getDeclaredConstructor();
  5. Object o = declaredConstructor.newInstance();
  6. Field[] fields = c.getDeclaredFields();
  7. for (Field f : fields) {
  8. String name = f.getName();
  9. Class<?> type = f.getType();
  10. switch (type) { // switch block
  11. case String.class:
  12. break;
  13. default:
  14. break;
  15. }
  16. if (type.equals(String.class)) { // if block
  17. f.set(o, name);
  18. } else if (type.equals(Integer.class)) {
  19. f.set(o, nextInteger());
  20. }
  21. }
  22. }
  23. ``` `switch` 块给出错误:
  24. 不兼容的类型。找到java.lang.class<capture<?>>,必需的字符、字节、短字符、int、字符、字节、短字符、整数、字符串或枚举'
  25. 但是 `if` block按预期工作。我想区别在于开关的工作原理是 `==` 如果有 `equals` . 是否可以使用 `switch` ?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题