static { getExtendsClause = getMethod(JCClassDecl.class, "getExtendsClause", new Class<?>[0]); getExtendsClause.setAccessible(true); if (getJavaCompilerVersion() < 8) { getEndPosition = getMethod(DiagnosticPosition.class, "getEndPosition", java.util.Map.class); storeEnd = getMethod(java.util.Map.class, "put", Object.class, Object.class); } else { getEndPosition = getMethod( DiagnosticPosition.class, "getEndPosition", "com.sun.tools.javac.tree.EndPosTable"); Method storeEndMethodTemp; Class<?> endPosTable; try { endPosTable = Class.forName("com.sun.tools.javac.tree.EndPosTable"); } catch (ClassNotFoundException ex) { throw sneakyThrow(ex); } try { storeEndMethodTemp = endPosTable.getMethod("storeEnd", JCTree.class, int.class); } catch (NoSuchMethodException e) { try { endPosTable = Class.forName("com.sun.tools.javac.parser.JavacParser$AbstractEndPosTable"); storeEndMethodTemp = endPosTable.getDeclaredMethod("storeEnd", JCTree.class, int.class); } catch (NoSuchMethodException ex) { throw sneakyThrow(ex); } catch (ClassNotFoundException ex) { throw sneakyThrow(ex); } } storeEnd = storeEndMethodTemp; } getEndPosition.setAccessible(true); storeEnd.setAccessible(true); }
private static Method getMethod(Class<?> clazz, String name, String... paramTypes) { try { Class<?>[] c = new Class[paramTypes.length]; for (int i = 0; i < paramTypes.length; i++) c[i] = Class.forName(paramTypes[i]); return clazz.getMethod(name, c); } catch (NoSuchMethodException e) { throw sneakyThrow(e); } catch (ClassNotFoundException e) { throw sneakyThrow(e); } }
private static Method getMethod(Class<?> clazz, String name, Class<?>... paramTypes) { try { return clazz.getMethod(name, paramTypes); } catch (NoSuchMethodException e) { throw sneakyThrow(e); } }
@SuppressWarnings("unchecked") private <T> T readObject(JCTree tree, String fieldName, T defaultValue) { Class<?> tClass = tree.getClass(); Map<String, Field> c = reflectionCache.get(tClass); if (c == null) reflectionCache.put(tClass, c = new HashMap<String, Field>()); Field f = c.get(fieldName); if (f == null) { try { f = tClass.getDeclaredField(fieldName); } catch (Exception e) { return defaultValue; } f.setAccessible(true); c.put(fieldName, f); } try { return (T) f.get(tree); } catch (Exception e) { return defaultValue; } }