Java 查看方法定义 Cannot infer type arguments for XXX<>报错如何解决

本文介绍了在遇到类同名前需添加包名以及参数类型错误时,如何利用Eclipse的Open Declaration和IDEA的Go To -> Declaration and Usages功能查看并修复问题。通过这些工具,开发者可以快速定位到方法定义,从而进行有效的代码调试和修正。

1、类同名 前面加上包名
2、参数类型错误
选中报错部分 右键
eclipse :Opean Declaration
IDEA : Go To -> Declaration and Usages

查看方法定义

Appid: __UNI__5D2350E HBuilderX版本号:4.87 云打包服务器SDK版本: 4.87 e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:23:28 Cannot infer type for this parameter. Specify it explicitly. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:24:17 Interface 'interface Project : Any' does not have constructors. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:25:17 Interface 'interface Project : Any' does not have constructors. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:26:17 Interface 'interface Project : Any' does not have constructors. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:57:37 Cannot infer type for this parameter. Specify it explicitly. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:57:37 Not enough information to infer type argument for 'T'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:57:62 Syntax error: Type expected. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:57:62 Syntax error: Incomplete code. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:63:13 Missing return statement. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:63:14 Unresolved reference. None of the following candidates is applicable because of a receiver type mismatch: fun Number.compareTo(other: Number): Int e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:66:21 'return' is prohibited here. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:66:28 Cannot infer type for this parameter. Specify it explicitly. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:66:28 Not enough information to infer type argument for 'E'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:69:17 'return' is prohibited here. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:78:17 Cannot infer type for this parameter. Specify it explicitly. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:78:20 No 'get' operator method providing array access. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:87:29 Cannot create an instance of an abstract class. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:87:36 Too many arguments for 'constructor(): Number'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:87:38 Unresolved reference 'detail'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:88:33 Unresolved reference 'isFinal'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:92:29 Cannot create an instance of an abstract class. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:92:36 Too many arguments for 'constructor(): Number'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:92:38 Unresolved reference 'detail'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:93:33 Unresolved reference 'fundingSource'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:102:21 Condition type mismatch: inferred type is 'String?' but 'Boolean' was expected. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:102:26 Unresolved reference 'projectName'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:103:40 Unresolved reference 'projectName'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:109:21 Condition type mismatch: inferred type is 'String?' but 'Boolean' was expected. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:109:26 Unresolved reference 'companyName'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:110:40 Unresolved reference 'companyName'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:116:26 Unresolved reference 'isFinal'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:120:33 Unresolved reference 'isFinal'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:126:26 Unresolved reference 'fundingSource'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:127:60 Unresolved reference 'fundingSource'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:128:25 Condition type mismatch: inferred type is 'String' but 'Boolean' was expected. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:153:21 Unresolved reference 'not' for operator '!'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:175:82 Unresolved reference 'projectName'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:176:53 Unresolved reference 'projectName'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:185:82 Unresolved reference 'companyName'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:186:53 Unresolved reference 'companyName'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:197:116 Unresolved reference 'isFinal'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:199:122 Unresolved reference 'isFinal'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:208:124 Unresolved reference 'fundingSource'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:210:128 Unresolved reference 'fundingSource'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:242:111 Cannot infer type for this parameter. Specify it explicitly. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:242:120 Cannot infer type for this parameter. Specify it explicitly. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:242:127 Cannot infer type for this parameter. Specify it explicitly. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:242:136 Cannot infer type for this parameter. Specify it explicitly. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:243:88 Unresolved reference 'id'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:247:111 Unresolved reference 'name'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:248:98 Unresolved reference 'company'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:249:102 Unresolved reference 'isFinal'. e: file://[PackagePath]/wgtRoot/__UNI__5D2350E/.uniappx/android/src/pages/query/query.kt:255:98 Unresolved reference 'fundingSource'.
最新发布
01-05
```java import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.*; import com.fasterxml.jackson.databind.module.SimpleModule; import java.io.*; import java.lang.reflect.Field; import java.nio.charset.StandardCharsets; import java.util.*; public class JsonFileToXmlConverter { private static final String ENTITY_PACKAGE = "com.mock.entry"; private static final ObjectMapper objectMapper; // 静态初始化:动态注册所有实体类的反序列化器(自动适配数组或对象) static { objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); SimpleModule module = new SimpleModule(); // 注册一个通用的反序列化器工厂,适用于所有在 com.mock.entry 包下的类 module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { Class<?> type = beanDesc.getBeanClass(); if (type.getName().startsWith(ENTITY_PACKAGE)) { // 显式指定泛型类型,避免编译器无法推断 return new GenericArrayOrObjectDeserializer<>(type, deserializer); } return deserializer; } }); objectMapper.registerModule(module); } public static void main(String[] args) { String uploadDirPath = "./uploads"; File uploadDir = new File(uploadDirPath); if (!uploadDir.exists() || !uploadDir.isDirectory()) { System.err.println("上传目录不存在: " + uploadDirPath); return; } File[] jsonFiles = uploadDir.listFiles((dir, name) -> name.toLowerCase().endsWith(".json")); if (jsonFiles == null) return; for (File jsonFile : jsonFiles) { try { String xmlString = processJsonFile(jsonFile); System.out.println("成功生成 XML:\n" + xmlString + "\n"); } catch (Exception e) { System.err.println("处理文件失败: " + jsonFile.getName() + " -> " + e.getMessage()); e.printStackTrace(); } } } public static String processJsonFile(File jsonFile) throws Exception { String fileNameNoExt = getFileNameWithoutExtension(jsonFile.getName()); Class<?> entityClass = findClassInPackage(ENTITY_PACKAGE, fileNameNoExt); if (entityClass == null) { throw new IllegalArgumentException("未找到与文件名匹配的实体类: " + fileNameNoExt); } String jsonContent = readFileAsString(jsonFile.getAbsolutePath()); Object instance = objectMapper.readValue(jsonContent, entityClass); return objectToXml(instance, "BODY"); } /** * 通用反序列化器:支持从数组中取第一个对象或直接解析对象 */ public static class GenericArrayOrObjectDeserializer<T> extends JsonDeserializer<T> { private final Class<T> clazz; private final JsonDeserializer<T> defaultDeserializer; @SuppressWarnings("unchecked") public GenericArrayOrObjectDeserializer(Class<?> clazz, JsonDeserializer<?> defaultDeserializer) { this.clazz = (Class<T>) clazz; this.defaultDeserializer = (JsonDeserializer<T>) defaultDeserializer; } @Override public T deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { JsonToken token = p.getCurrentToken(); // 情况1:是数组,尝试读取第一个元素作为对象 if (token == JsonToken.START_ARRAY) { while (p.nextToken() != JsonToken.END_ARRAY) { if (p.getCurrentToken() == JsonToken.START_OBJECT) { return defaultDeserializer.deserialize(p, ctxt); } } // 空数组则返回新实例 try { return clazz.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException("无法创建类实例: " + clazz.getName(), e); } } // 情况2:是对象,正常反序列化 if (token == JsonToken.START_OBJECT) { return defaultDeserializer.deserialize(p, ctxt); } // 其他情况报错 throw new JsonMappingException(p, "期望是对象或数组,但得到了: " + token); } } private static Class<?> findClassInPackage(String packageName, String fileName) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String path = packageName.replace('.', '/'); Enumeration<URL> resources = classLoader.getResources(path); List<File> dirs = new ArrayList<>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); if ("file".equals(resource.getProtocol())) { dirs.add(new File(resource.getFile())); } } for (File directory : dirs) { List<Class<?>> classes = findClasses(directory, packageName); for (Class<?> clazz : classes) { if (clazz.getSimpleName().equalsIgnoreCase(fileName)) { return clazz; } } } return null; } private static List<Class<?>> findClasses(File dir, String packageName) throws ClassNotFoundException { List<Class<?>> classes = new ArrayList<>(); if (!dir.exists()) return classes; File[] files = dir.listFiles(); if (files == null) return classes; for (File file : files) { if (file.isDirectory()) { classes.addAll(findClasses(file, packageName + "." + file.getName())); } else if (file.getName().endsWith(".class")) { String className = file.getName().substring(0, file.getName().length() - 6); try { Class<?> clazz = Class.forName(packageName + "." + className); classes.add(clazz); } catch (ClassNotFoundException | NoClassDefFoundError e) { System.err.println("无法加载类: " + packageName + "." + className); } } } return classes; } private static String readFileAsString(String filePath) throws IOException { StringBuilder content = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader( new FileInputStream(filePath), StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { content.append(line).append("\n"); } } if (content.length() > 0 && content.charAt(content.length() - 1) == '\n') { content.setLength(content.length() - 1); } return content.toString(); } private static String getFileNameWithoutExtension(String fileName) { int lastDotIndex = fileName.lastIndexOf('.'); return (lastDotIndex == -1) ? fileName : fileName.substring(0, lastDotIndex); } private static String objectToXml(Object obj, String rootName) throws IllegalAccessException { StringBuilder xml = new StringBuilder(); if (rootName != null) { xml.append("<").append(rootName).append(">\n"); } Class<?> clazz = obj.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); Object value = field.get(obj); if (value == null) continue; String fieldName = field.getName(); if (value instanceof List) { xml.append(" <").append(fieldName).append(">\n"); for (Object item : (List<?>) value) { xml.append(" <ITEM>\n"); String nestedXml = objectToXml(item, null); String indentedNestedXml = addIndent(nestedXml, 6); xml.append(indentedNestedXml).append("\n"); xml.append(" </ITEM>\n"); } xml.append(" </").append(fieldName).append(">\n"); } else if (isPrimitiveOrWrapper(value.getClass()) || value instanceof String) { xml.append(" <").append(fieldName).append(">") .append(escapeXml(value.toString())) .append("</").append(fieldName).append(">\n"); } else { xml.append(" <").append(fieldName).append(">\n"); String nestedXml = objectToXml(value, null); String indentedNestedXml = addIndent(nestedXml, 4); xml.append(indentedNestedXml).append("\n"); xml.append(" </").append(fieldName).append(">\n"); } } if (rootName != null) { xml.append("</").append(rootName).append(">"); } return xml.toString(); } private static String addIndent(String input, int spaces) { StringBuilder result = new StringBuilder(); String indent = String.join("", Collections.nCopies(spaces, " ")); String[] lines = input.split("\r?\n"); for (int i = 0; i < lines.length; i++) { result.append(indent).append(lines[i]); if (i < lines.length - 1) { result.append("\n"); } } return result.toString(); } private static boolean isPrimitiveOrWrapper(Class<?> type) { return type.isPrimitive() || Number.class.isAssignableFrom(type) || type.equals(Boolean.class) || type.equals(Character.class) || type.equals(String.class); } private static String escapeXml(String s) { return s.replace("&", "&") .replace("<", "<") .replace(">", ">") .replace("\"", """) .replace("'", "&apos;"); } } ``` --- ### ✅ 回答问题:`new GenericArrayOrObjectDeserializer<>(type, deserializer)` 报错Cannot infer type arguments” 是为什么?如何解决? #### ❌ 错误原因: 虽然你在构造函数中传入了 `Class<?> type` 和 `JsonDeserializer<?> deserializer`,但 Java 编译器无法自动推断出泛型 `T` 的具体类型,因为: - `deserializer` 是原始类型 `JsonDeserializer<?>` - `type` 是 `Class<?>`,没有绑定到泛型参数 `T` - 构造函数声明为 `<T>`,但上下文无足够信息进行类型推导 所以编译器报错:**“Cannot infer type arguments”** --- ### ✅ 正确解决方案:显式定义带类型擦除的构造函数 我们修改 `GenericArrayOrObjectDeserializer` 的构造函数,**不依赖泛型推导**,而是通过强制类型转换来实现运行时绑定。 #### ✅ 修改后的构造函数: ```java @SuppressWarnings("unchecked") public GenericArrayOrObjectDeserializer(Class<?> clazz, JsonDeserializer<?> defaultDeserializer) { this.clazz = (Class<T>) clazz; this.defaultDeserializer = (JsonDeserializer<T>) defaultDeserializer; } ``` #### ✅ 关键点说明: | 要点 | 说明 | |------|------| | ✅ 不使用泛型推导 | 直接接收原始类型,手动强转 | | ✅ 使用 `@SuppressWarnings("unchecked")` | 屏蔽类型安全警告(你已确保逻辑正确) | | ✅ 利用 Jackson 内部机制 | `defaultDeserializer` 实际上已经是对应类型的反序列化器 | | ✅ 类型安全由调用方保证 | 只用于 `com.mock.entry` 下的真实实体类 | --- ### ✅ 为什么可以强转? 因为在 Jackson 反序列化过程中: - `BeanDescription` 提供的是具体的 `Class<T>` - `JsonDeserializer<?>` 实际上就是 `JsonDeserializer<T>` 的实例 - 所以 `(JsonDeserializer<T>)` 强转是类型安全的 --- ### ✅ 对比:错误写法 vs 正确写法 #### ❌ 错误:依赖泛型推导(编译不过) ```java return new GenericArrayOrObjectDeserializer<>(type, deserializer); // 编译器无法推断 T ``` #### ✅ 正确:构造函数接受原始类型并强转 ```java public GenericArrayOrObjectDeserializer(Class<?> clazz, JsonDeserializer<?> defaultDeserializer) { this.clazz = (Class<T>) clazz; this.defaultDeserializer = (JsonDeserializer<T>) defaultDeserializer; } ``` 此时即使你不写 `<>` 中的具体类型,也能正确创建实例。 --- ### ✅ 补充建议 1. **避免使用 `.newInstance()`** 已废弃,改用 `clazz.getDeclaredConstructor().newInstance()`(如代码所示) 2. **添加空构造函数检查** 确保实体类有默认构造函数,否则反射会失败 3. **日志提示更友好异常信息** 建议捕获 `InvocationTargetException` 等并输出类名 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

隔壁de小刘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值