From 02993bf2cfaa3c8c5496482798bd35069ac0df37 Mon Sep 17 00:00:00 2001 From: Eric Milles Date: Sun, 22 Apr 2018 10:31:54 -0500 Subject: [PATCH] Refactor of ReflectionUtils to reduce need for type casting --- .../tests/builder/BuilderTestSuite.java | 99 +++++++++------- .../tests/locations/LocationSupportTests.java | 5 +- .../tests/basic/GroovyCompilerTestSuite.java | 3 +- .../internal/MultiplexingIndexingParser.java | 2 +- ...tiplexingSourceElementRequestorParser.java | 8 +- .../compiler/GroovyClassLoaderFactory.java | 4 +- .../compiler/ast/JDTClassNodeBuilder.java | 4 +- .../jdt/groovy/model/GrabDeclaration.java | 4 +- .../groovy/model/GroovyCompilationUnit.java | 2 +- .../jdt/groovy/core/util/ReflectionUtils.java | 107 ++++++++++-------- .../search/FieldReferenceSearchRequestor.java | 6 +- .../MethodReferenceSearchRequestor.java | 4 +- .../jdt/groovy/search/SimpleTypeLookup.java | 2 +- .../TypeInferencingVisitorWithRequestor.java | 3 +- .../search/TypeReferenceSearchRequestor.java | 4 +- .../groovy/search/TypeRequestorFactory.java | 6 +- .../test/debug/ConsoleLineTrackerTests.groovy | 6 +- .../test/ui/GroovyEditorTestSuite.groovy | 4 +- .../wizards/NewGroovyTypeWizardTests.groovy | 4 +- .../GroovyJavaMethodCompletionProposal.java | 6 +- .../creators/CategoryProposalCreator.java | 10 +- ...llectorTypeCompletionProcessorFactory.java | 5 +- .../core/builder/GroovyNameLookup.java | 12 +- .../core/compiler/GroovySnippetParser.java | 4 +- .../ExtractGroovyConstantRefactoring.java | 13 +-- ...RenameLocalGroovyVariableContribution.java | 6 +- .../ClassFileEditorAdapterFactory.java | 4 +- .../eclipse/debug/ui/EnsureJUnitFont.java | 4 +- .../GroovyBreakpointRulerActionDelegate.java | 2 +- .../editor/GroovyAutoIndentStrategy.java | 7 +- .../GroovyAwareFoldingStructureProvider.java | 4 +- .../eclipse/editor/GroovyConfiguration.java | 7 +- .../groovy/eclipse/editor/GroovyEditor.java | 26 ++--- .../GroovySemanticReconciler.java | 7 +- .../launchers/GroovyShellLauncherTab.java | 22 +--- .../actions/AddImportOnSelectionAction.java | 4 +- .../actions/AddImportOnSelectionAdapter.java | 6 +- .../actions/GroovyRenameLinkedMode.java | 12 +- .../actions/OrganizeGroovyImportsAction.java | 4 +- 39 files changed, 225 insertions(+), 217 deletions(-) diff --git a/base-test/org.eclipse.jdt.groovy.core.tests.builder/src/org/eclipse/jdt/core/groovy/tests/builder/BuilderTestSuite.java b/base-test/org.eclipse.jdt.groovy.core.tests.builder/src/org/eclipse/jdt/core/groovy/tests/builder/BuilderTestSuite.java index c19a05bb33..ed1d549b55 100644 --- a/base-test/org.eclipse.jdt.groovy.core.tests.builder/src/org/eclipse/jdt/core/groovy/tests/builder/BuilderTestSuite.java +++ b/base-test/org.eclipse.jdt.groovy.core.tests.builder/src/org/eclipse/jdt/core/groovy/tests/builder/BuilderTestSuite.java @@ -80,63 +80,82 @@ public final void setUpTestCase() { @After public final void tearDownTestCase() { env.resetWorkspace(); - // Discard primary working copies and copies with owner left from failed tests - ICompilationUnit[] wcs = null; - int i = 0; - do { - wcs = JavaModelManager.getJavaModelManager().getWorkingCopies(null, true); - if (wcs != null) { - for (ICompilationUnit workingCopy : wcs) { - try { - workingCopy.discardWorkingCopy(); - workingCopy.close(); - } catch (Exception e) { - e.printStackTrace(); + try { + // discard primary working copies and copies with owner left from failed tests + ICompilationUnit[] wcs = null; + int i = 0; + do { + wcs = JavaModelManager.getJavaModelManager().getWorkingCopies(null, true); + if (wcs != null) { + for (ICompilationUnit workingCopy : wcs) { + try { + workingCopy.discardWorkingCopy(); + workingCopy.close(); + } catch (Exception e) { + e.printStackTrace(); + } } } - } - i += 1; - if (i > 20 && wcs != null) { - Assert.fail("Could not delete working copies " + wcs); - } - } while (wcs != null && wcs.length > 0); - Assert.assertTrue("ModuleNodeMapper should be empty when there are no working copies", moduleNodeMapperCacheSize >= ModuleNodeMapper.size()); - JavaCore.setOptions(JavaCore.getDefaultOptions()); + i += 1; + if (i > 20 && wcs != null) { + Assert.fail("Could not delete working copies " + wcs); + } + } while (wcs != null && wcs.length > 0); + + Assert.assertTrue("ModuleNodeMapper should be empty when there are no working copies", moduleNodeMapperCacheSize >= ModuleNodeMapper.size()); + } finally { + JavaCore.setOptions(JavaCore.getDefaultOptions()); + } } protected final void cleanBuild() { debugRequestor.clearResult(); debugRequestor.activate(); - env.cleanBuild(); - debugRequestor.deactivate(); + try { + env.cleanBuild(); + } finally { + debugRequestor.deactivate(); + } } protected final void fullBuild() { debugRequestor.clearResult(); debugRequestor.activate(); - env.fullBuild(); - debugRequestor.deactivate(); + try { + env.fullBuild(); + } finally { + debugRequestor.deactivate(); + } } protected final void fullBuild(IPath projectPath) { debugRequestor.clearResult(); debugRequestor.activate(); - env.fullBuild(projectPath); - debugRequestor.deactivate(); + try { + env.fullBuild(projectPath); + } finally { + debugRequestor.deactivate(); + } } protected final void incrementalBuild() { debugRequestor.clearResult(); debugRequestor.activate(); - env.incrementalBuild(); - debugRequestor.deactivate(); + try { + env.incrementalBuild(); + } finally { + debugRequestor.deactivate(); + } } protected final void incrementalBuild(IPath projectPath) { debugRequestor.clearResult(); debugRequestor.activate(); - env.incrementalBuild(projectPath); - debugRequestor.deactivate(); + try { + env.incrementalBuild(projectPath); + } finally { + debugRequestor.deactivate(); + } } protected void executeClass(IPath projectPath, String className, String expectingOutput, String expectedError) { @@ -163,7 +182,7 @@ protected void executeClass(IPath projectPath, String className, String expectin if (expectedError == null && actualError.length() != 0) { if (actualError.trim().endsWith( "WARNING: Module [groovy-all] - Unable to load extension class [org.codehaus.groovy.runtime.NioGroovyMethods]")) { - // Allow this it indicates (usually) running the tests with groovy 2.3 on a pre 1.7 vm + // allow this it indicates (usually) running the tests with groovy 2.3 on a pre 1.7 vm } else { Assert.fail("unexpected error : " + actualError); } @@ -187,7 +206,7 @@ protected void executeClass(IPath projectPath, String className, String expectin //-------------------------------------------------------------------------- protected final void expectingCompiledClasses(String... expected) { - String[] actual = (String[]) ReflectionUtils.executeNoArgPrivateMethod(debugRequestor.getClass(), "getCompiledClasses", debugRequestor); + String[] actual = ReflectionUtils.executePrivateMethod(debugRequestor.getClass(), "getCompiledClasses", debugRequestor); Util.sort(actual); Util.sort(expected); expectingCompiling(actual, expected, "unexpected recompiled units. lenExpected=" + expected.length + " lenActual=" + actual.length); @@ -195,19 +214,17 @@ protected final void expectingCompiledClasses(String... expected) { private void expectingCompiling(String[] actual, String[] expected, String message) { StringBuilder actualBuffer = new StringBuilder("{"); - for (int i = 0; i < actual.length; i++) { - if (i > 0) - actualBuffer.append(","); + for (int i = 0; i < actual.length; i += 1) { + if (i > 0) actualBuffer.append(","); actualBuffer.append(actual[i]); } - actualBuffer.append('}'); + actualBuffer.append("}"); StringBuilder expectedBuffer = new StringBuilder("{"); - for (int i = 0; i < expected.length; i++) { - if (i > 0) - expectedBuffer.append(","); + for (int i = 0; i < expected.length; i += 1) { + if (i > 0) expectedBuffer.append(","); expectedBuffer.append(expected[i]); } - expectedBuffer.append('}'); + expectedBuffer.append("}"); Assert.assertEquals(message, expectedBuffer.toString(), actualBuffer.toString()); } @@ -235,7 +252,7 @@ protected final void expectingSpecificProblemFor(IPath root, Problem problem) { protected void expectingSpecificProblemsFor(IPath root, Problem[] problems) { Problem[] rootProblems = env.getProblemsFor(root); - next : for (int i = 0; i < problems.length; i += 1) { + next: for (int i = 0; i < problems.length; i += 1) { Problem problem = problems[i]; for (int j = 0; j < rootProblems.length; j += 1) { Problem rootProblem = rootProblems[j]; diff --git a/base-test/org.eclipse.jdt.groovy.core.tests.builder/src/org/eclipse/jdt/core/groovy/tests/locations/LocationSupportTests.java b/base-test/org.eclipse.jdt.groovy.core.tests.builder/src/org/eclipse/jdt/core/groovy/tests/locations/LocationSupportTests.java index 2d2d980dd0..c63d60eac0 100644 --- a/base-test/org.eclipse.jdt.groovy.core.tests.builder/src/org/eclipse/jdt/core/groovy/tests/locations/LocationSupportTests.java +++ b/base-test/org.eclipse.jdt.groovy.core.tests.builder/src/org/eclipse/jdt/core/groovy/tests/locations/LocationSupportTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -235,8 +235,7 @@ public void testGRECLIPSE887_ImportStatements() throws Exception { GroovyCompilationUnitDeclaration cud = new GroovyCompilationUnitDeclaration(null, null, -1, null, null, null) {{ GroovyCompilationUnitDeclaration.UnitPopulator cup = new GroovyCompilationUnitDeclaration.UnitPopulator(); ReflectionUtils.setPrivateField(cup.getClass(), "unitDeclaration", cup, this); - ReflectionUtils.executePrivateMethod(cup.getClass(), "createImportDeclarations", - new Class[] {ModuleNode.class}, cup, new Object[] {module}); + ReflectionUtils.executePrivateMethod(cup.getClass(), "createImportDeclarations", new Class[] {ModuleNode.class}, cup, new Object[] {module}); }}; assertEquals(module.getImport("List").getStart(), cud.imports[0].declarationSourceStart); diff --git a/base-test/org.eclipse.jdt.groovy.core.tests.compiler/src/org/eclipse/jdt/groovy/core/tests/basic/GroovyCompilerTestSuite.java b/base-test/org.eclipse.jdt.groovy.core.tests.compiler/src/org/eclipse/jdt/groovy/core/tests/basic/GroovyCompilerTestSuite.java index 580e9026d2..269ac7142e 100644 --- a/base-test/org.eclipse.jdt.groovy.core.tests.compiler/src/org/eclipse/jdt/groovy/core/tests/basic/GroovyCompilerTestSuite.java +++ b/base-test/org.eclipse.jdt.groovy.core.tests.compiler/src/org/eclipse/jdt/groovy/core/tests/basic/GroovyCompilerTestSuite.java @@ -187,9 +187,8 @@ protected final boolean isAtLeastJava(long level) { return complianceLevel >= level; } - @SuppressWarnings("unchecked") protected final Map getCompilerOptions() { - return (Map) ReflectionUtils.executeNoArgPrivateMethod(AbstractRegressionTest.class, "getCompilerOptions", testDriver); + return ReflectionUtils.executePrivateMethod(AbstractRegressionTest.class, "getCompilerOptions", testDriver); } protected final void runConformTest(String[] sources) { diff --git a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/integration/internal/MultiplexingIndexingParser.java b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/integration/internal/MultiplexingIndexingParser.java index c8b6a58627..5739cea4df 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/integration/internal/MultiplexingIndexingParser.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/integration/internal/MultiplexingIndexingParser.java @@ -46,7 +46,7 @@ public class MultiplexingIndexingParser extends IndexingParser { public MultiplexingIndexingParser(ISourceElementRequestor requestor, IProblemFactory problemFactory, CompilerOptions options, boolean reportLocalDeclarations, boolean optimizeStringLiterals, boolean useSourceJavadocParser) { super(requestor, problemFactory, options, reportLocalDeclarations, optimizeStringLiterals, useSourceJavadocParser); - this.notifier = (SourceElementNotifier) ReflectionUtils.getPrivateField(SourceElementParser.class, "notifier", this); + this.notifier = ReflectionUtils.getPrivateField(SourceElementParser.class, "notifier", this); this.groovyReportReferenceInfo = reportLocalDeclarations; this.requestor = requestor; } diff --git a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/integration/internal/MultiplexingSourceElementRequestorParser.java b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/integration/internal/MultiplexingSourceElementRequestorParser.java index 99afad2769..4e57a8d633 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/integration/internal/MultiplexingSourceElementRequestorParser.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/integration/internal/MultiplexingSourceElementRequestorParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -77,9 +77,9 @@ protected void notifySourceElementRequestor(ImportReference importReference, boo super.notifySourceElementRequestor(importReference, isPackage); if (!isPackage && importReference.annotations != null) { try { - ImportContainerInfo importContainerInfo = (ImportContainerInfo) ReflectionUtils.getPrivateField(CompilationUnitStructureRequestor.class, "importContainerInfo", compUnitStructureRequestor); + ImportContainerInfo importContainerInfo = ReflectionUtils.getPrivateField(CompilationUnitStructureRequestor.class, "importContainerInfo", compUnitStructureRequestor); for (Annotation annotation : importReference.annotations) { - IJavaElement[] imports = (IJavaElement[]) ReflectionUtils.throwableExecutePrivateMethod(CompilationUnitStructureRequestor.class, "getChildren", new Class[] {Object.class}, compUnitStructureRequestor, new Object[] {importContainerInfo}); + IJavaElement[] imports = ReflectionUtils.throwableExecutePrivateMethod(CompilationUnitStructureRequestor.class, "getChildren", new Class[] {Object.class}, compUnitStructureRequestor, new Object[] {importContainerInfo}); //requestor.acceptAnnotation(Annotation annotation, AnnotatableInfo parentInfo, JavaElement parentHandle); ReflectionUtils.throwableExecutePrivateMethod(CompilationUnitStructureRequestor.class, "acceptAnnotation", @@ -115,7 +115,7 @@ public CompilationUnitDeclaration parseCompilationUnit(ICompilationUnit unit, bo GroovyParser groovyParser = new GroovyParser(this.groovyParser.requestor, options, problemReporter, false, true); CompilationUnitDeclaration cud = groovyParser.dietParse(unit, compilationResult); - SourceElementNotifier notifier = (SourceElementNotifier) ReflectionUtils.getPrivateField(SourceElementParser.class, "notifier", this); + SourceElementNotifier notifier = ReflectionUtils.getPrivateField(SourceElementParser.class, "notifier", this); notifier.notifySourceElementRequestor(cud, 0, unit.getContents().length, groovyReportReferenceInfo, createSourceEnds(cud), Collections.EMPTY_MAP); // we don't care about the @category tag, so pass empty map return cud; diff --git a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/GroovyClassLoaderFactory.java b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/GroovyClassLoaderFactory.java index 66fddb83e6..0ddab7cdd8 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/GroovyClassLoaderFactory.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/GroovyClassLoaderFactory.java @@ -122,7 +122,7 @@ private GroovyClassLoader[] getBatchGroovyClassLoaders(CompilerConfiguration com nameEnvironment = ((INameEnvironment[]) ReflectionUtils.getPrivateField(nameEnvironment.getClass(), "classLibs", nameEnvironment))[0]; } if (nameEnvironment instanceof FileSystem) { - FileSystem.Classpath[] classpaths = (FileSystem.Classpath[]) ReflectionUtils.getPrivateField(FileSystem.class, "classpaths", nameEnvironment); + FileSystem.Classpath[] classpaths = ReflectionUtils.getPrivateField(FileSystem.class, "classpaths", nameEnvironment); if (classpaths != null) { batchLoader = new GroovyClassLoader(); for (FileSystem.Classpath classpath : classpaths) { @@ -194,7 +194,7 @@ private static void calculateClasspath(IJavaProject javaProject, Set cla private static IRuntimeClasspathEntry[] resolveRuntimeClasspathEntry(IRuntimeClasspathEntry classpathEntry, IJavaProject javaProject) throws Exception { //return JavaRuntime.resolveRuntimeClasspathEntry(classpathEntry, javaProject); // indirect dependency on org.eclipse.debug.core.ILaunchConfiguration - return (IRuntimeClasspathEntry[]) ReflectionUtils.throwableExecutePrivateMethod(JavaRuntime.class, "resolveRuntimeClasspathEntry", new Class[] {IRuntimeClasspathEntry.class, IJavaProject.class}, JavaRuntime.class, new Object[] {classpathEntry, javaProject}); + return ReflectionUtils.throwableExecutePrivateMethod(JavaRuntime.class, "resolveRuntimeClasspathEntry", new Class[] {IRuntimeClasspathEntry.class, IJavaProject.class}, JavaRuntime.class, new Object[] {classpathEntry, javaProject}); } private static String getAbsoluteLocation(IRuntimeClasspathEntry classpathEntry) { diff --git a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/ast/JDTClassNodeBuilder.java b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/ast/JDTClassNodeBuilder.java index 5405b5af98..6923332abc 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/ast/JDTClassNodeBuilder.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/internal/compiler/ast/JDTClassNodeBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -157,7 +157,7 @@ protected TypeBinding toRawType(TypeBinding tb) { return fb; } else if (tb instanceof BinaryTypeBinding) { if (tb.isGenericType()) { - LookupEnvironment le = (LookupEnvironment) ReflectionUtils.getPrivateField(BinaryTypeBinding.class, "environment", tb); + LookupEnvironment le = ReflectionUtils.getPrivateField(BinaryTypeBinding.class, "environment", tb); return le.convertToRawType(tb, false); } else { return tb; diff --git a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/model/GrabDeclaration.java b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/model/GrabDeclaration.java index e1271363c9..958f266057 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/model/GrabDeclaration.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/model/GrabDeclaration.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -61,6 +61,6 @@ protected char getHandleMementoDelimiter() { @Override public ISourceRange getNameRange() throws JavaModelException { - return (ISourceRange) ReflectionUtils.executeNoArgPrivateMethod(ImportDeclarationElementInfo.class, "getNameRange", getElementInfo()); + return ReflectionUtils.executePrivateMethod(ImportDeclarationElementInfo.class, "getNameRange", getElementInfo()); } } diff --git a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/model/GroovyCompilationUnit.java b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/model/GroovyCompilationUnit.java index f36ea50205..3d6dc4c178 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/model/GroovyCompilationUnit.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/codehaus/jdt/groovy/model/GroovyCompilationUnit.java @@ -237,7 +237,7 @@ protected boolean buildStructure(OpenableElementInfo info, IProgressMonitor pm, createAST = ((Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "astLevel", astHolder)) != NO_AST; resolveBindings = (Boolean) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "resolveBindings", astHolder); reconcileFlags = (Integer) ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "reconcileFlags", astHolder); - problems = HashMap.class.cast(ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "problems", astHolder)); + problems = ReflectionUtils.getPrivateField(ASTHolderCUInfo.class, "problems", astHolder); } else { createAST = false; resolveBindings = false; diff --git a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/core/util/ReflectionUtils.java b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/core/util/ReflectionUtils.java index fea4c23023..ab7cda01cd 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/core/util/ReflectionUtils.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/core/util/ReflectionUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -36,8 +36,7 @@ public class ReflectionUtils { private ReflectionUtils() {} public static Class[] getAllInterfaces(Class clazz) { - @SuppressWarnings("rawtypes") - Set interfaces = new LinkedHashSet<>(); + Set> interfaces = new LinkedHashSet<>(); do { Collections.addAll(interfaces, clazz.getInterfaces()); @@ -50,8 +49,10 @@ public static Class[] getAllInterfaces(Class clazz) { public static Constructor getConstructor(Class instanceType, Class... parameterTypes) { try { Constructor ctor = instanceType.getDeclaredConstructor(parameterTypes); - ctor.setAccessible(true); + if (!ctor.isAccessible()) ctor.setAccessible(true); return ctor; + } catch (RuntimeException e) { + throw e; } catch (Exception e) { throw new RuntimeException(e); } @@ -62,8 +63,8 @@ public static T invokeConstructor(Constructor ctor, Object... args) { return ctor.newInstance(args); } catch (RuntimeException e) { throw e; - } catch (Throwable t) { - throw new RuntimeException(t); + } catch (Exception e) { + throw new RuntimeException(e); } } @@ -76,69 +77,85 @@ public static T invokeConstructor(Class instanceType, Class[] paramete } } - public static Object getPrivateField(Class clazz, String fieldName, Object target) { - String key = clazz.getCanonicalName() + fieldName; - Field field = FIELDS.get(key); + public static R getPrivateField(Class clazz, String fieldName, T target) { try { - if (field == null) { - field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - FIELDS.put(key, field); - } - return field.get(target); + Field field = getDeclaredField(clazz, fieldName); + + @SuppressWarnings("unchecked") + R result = (R) field.get(target); + return result; } catch (Exception e) { log("Error getting private field '" + fieldName + "' on class " + clazz, e); + return null; } - return null; } - public static void setPrivateField(Class clazz, String fieldName, Object target, Object newValue) { - String key = clazz.getCanonicalName() + fieldName; - Field field = FIELDS.get(key); + public static void setPrivateField(Class clazz, String fieldName, T target, Object value) { try { - if (field == null) { - field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - FIELDS.put(key, field); - } - field.set(target, newValue); + Field field = getDeclaredField(clazz, fieldName); + + field.set(target, value); } catch (Exception e) { log("Error setting private field '" + fieldName + "' on class " + clazz, e); } } - public static Object executeNoArgPrivateMethod(Class clazz, String methodName, Object target) { + public static R executePrivateMethod(Class clazz, String methodName, T target) { return executePrivateMethod(clazz, methodName, NO_TYPES, target, NO_ARGS); } - public static Object executePrivateMethod(Class clazz, String methodName, Class[] types, Object target, Object[] args) { - // forget caching for now... + public static R executePrivateMethod(Class clazz, String methodName, Class[] paramTypes, T target, Object[] args) { try { - Method method = clazz.getDeclaredMethod(methodName, types); - method.setAccessible(true); - return method.invoke(target, args); + Method method = getDeclaredMethod(clazz, methodName, paramTypes); + + @SuppressWarnings("unchecked") + R result = (R) method.invoke(target, args); + return result; } catch (Exception e) { log("Error executing private method '" + methodName + "' on class " + clazz, e); return null; } } - public static Object throwableExecutePrivateMethod(Class clazz, String methodName, Class[] types, T target, Object[] args) throws Exception { - // forget caching for now... - Method method = clazz.getDeclaredMethod(methodName, types); - method.setAccessible(true); - return method.invoke(target, args); + public static R throwableExecutePrivateMethod(Class clazz, String methodName, Class[] paramTypes, T target, Object[] args) throws Exception { + Method method = getDeclaredMethod(clazz, methodName, paramTypes); + + @SuppressWarnings("unchecked") + R result = (R) method.invoke(target, args); + return result; } - public static Object throwableGetPrivateField(Class clazz, String fieldName, T target) throws Exception { - String key = clazz.getCanonicalName() + fieldName; - Field field = FIELDS.get(key); - if (field == null) { - field = clazz.getDeclaredField(fieldName); - field.setAccessible(true); - FIELDS.put(key, field); - } - return field.get(target); + public static R throwableGetPrivateField(Class clazz, String fieldName, T target) throws Exception { + Field field = getDeclaredField(clazz, fieldName); + + @SuppressWarnings("unchecked") + R result = (R) field.get(target); + return result; + } + + //-------------------------------------------------------------------------- + + private static Field getDeclaredField(Class clazz, String field) throws Exception { + return FIELDS.computeIfAbsent(clazz.getCanonicalName() + field, k -> { + try { + Field f = clazz.getDeclaredField(field); + if (!f.isAccessible()) f.setAccessible(true); + return f; + + } catch (NoSuchFieldException e) { + log("Error finding field '" + field + "' on class " + clazz.getName(), e); + return null; + + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + } + + private static Method getDeclaredMethod(Class clazz, String method, Class... paramTypes) throws Exception { + Method m = clazz.getDeclaredMethod(method, paramTypes); + if (!m.isAccessible()) m.setAccessible(true); + return m; } private static void log(String message, Throwable throwable) { diff --git a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/FieldReferenceSearchRequestor.java b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/FieldReferenceSearchRequestor.java index c7969ceb62..4d321a149c 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/FieldReferenceSearchRequestor.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/FieldReferenceSearchRequestor.java @@ -54,11 +54,11 @@ public FieldReferenceSearchRequestor(FieldPattern pattern, SearchRequestor reque this.requestor = requestor; this.participant = participant; - char[] arr = (char[]) ReflectionUtils.getPrivateField(VariablePattern.class, "name", pattern); + char[] arr = ReflectionUtils.getPrivateField(VariablePattern.class, "name", pattern); fieldName = String.valueOf(arr); - arr = (char[]) ReflectionUtils.getPrivateField(FieldPattern.class, "declaringSimpleName", pattern); + arr = ReflectionUtils.getPrivateField(FieldPattern.class, "declaringSimpleName", pattern); String declaringSimpleName = ((arr == null || arr.length == 0) ? "" : String.valueOf(arr)); - arr = (char[]) ReflectionUtils.getPrivateField(FieldPattern.class, "declaringQualification", pattern); + arr = ReflectionUtils.getPrivateField(FieldPattern.class, "declaringQualification", pattern); String declaringQualification = ((arr == null || arr.length == 0) ? "" : (String.valueOf(arr) + ".")); declaringQualifiedName = declaringQualification + declaringSimpleName; diff --git a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/MethodReferenceSearchRequestor.java b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/MethodReferenceSearchRequestor.java index c395d96262..9af7264125 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/MethodReferenceSearchRequestor.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/MethodReferenceSearchRequestor.java @@ -75,7 +75,7 @@ public MethodReferenceSearchRequestor(MethodPattern pattern, SearchRequestor req this.methodName = String.valueOf(pattern.selector); String[] parameterTypeSignatures = getParameterTypeSignatures(pattern); - IType declaringType = (IType) ReflectionUtils.getPrivateField(MethodPattern.class, "declaringType", pattern); + IType declaringType = ReflectionUtils.getPrivateField(MethodPattern.class, "declaringType", pattern); char[] declaringQualifiedName = null; @@ -154,7 +154,7 @@ protected static String[] getParameterTypeNames(MethodPattern pattern, String[] } protected static String[] getParameterTypeSignatures(MethodPattern pattern) { - char[][][] signatures = (char[][][]) ReflectionUtils.getPrivateField(MethodPattern.class, "parametersTypeSignatures", pattern); + char[][][] signatures = ReflectionUtils.getPrivateField(MethodPattern.class, "parametersTypeSignatures", pattern); int n = (signatures == null ? 0 : signatures.length); String[] parameterTypeSignatures = new String[n]; for (int i = 0; i < n; i += 1) { diff --git a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/SimpleTypeLookup.java b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/SimpleTypeLookup.java index 40ddb5077e..276a9c5368 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/SimpleTypeLookup.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/SimpleTypeLookup.java @@ -712,7 +712,7 @@ protected static MethodNode getMethodTarget(Expression expr) { } else { StatementMeta meta = expr.getNodeMetaData(StatementMeta.class); if (meta != null) { - MethodNode target = (MethodNode) ReflectionUtils.getPrivateField(StatementMeta.class, "target", meta); + MethodNode target = ReflectionUtils.getPrivateField(StatementMeta.class, "target", meta); return target; } } diff --git a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeInferencingVisitorWithRequestor.java b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeInferencingVisitorWithRequestor.java index 4210703a20..969f25ed43 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeInferencingVisitorWithRequestor.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeInferencingVisitorWithRequestor.java @@ -2376,8 +2376,7 @@ private boolean isPrimaryExpression(Expression node) { // statically-compiled assignment chains need a little help if (!(node instanceof TupleExpression) && expr.getRightExpression() instanceof ListOfExpressionsExpression) { - @SuppressWarnings("unchecked") - List list = (List) ReflectionUtils.getPrivateField( + List list = ReflectionUtils.getPrivateField( ListOfExpressionsExpression.class, "expressions", expr.getRightExpression()); // list.get(0) should be TemporaryVariableExpression return (node != list.get(1) && list.get(1) instanceof MethodCallExpression); diff --git a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeReferenceSearchRequestor.java b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeReferenceSearchRequestor.java index 3510b68f8b..3cbedea4be 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeReferenceSearchRequestor.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeReferenceSearchRequestor.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ public TypeReferenceSearchRequestor(TypeReferencePattern pattern, SearchRequesto } protected final char[] extractArray(TypeReferencePattern pattern, String fieldName) { - char[] arr = (char[]) ReflectionUtils.getPrivateField(TypeReferencePattern.class, fieldName, pattern); + char[] arr = ReflectionUtils.getPrivateField(TypeReferencePattern.class, fieldName, pattern); if (!isCaseSensitive) { arr = CharOperation.toLowerCase(arr); } diff --git a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeRequestorFactory.java b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeRequestorFactory.java index 8c6e711b05..0bf9b67caa 100644 --- a/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeRequestorFactory.java +++ b/base/org.eclipse.jdt.groovy.core/src/org/eclipse/jdt/groovy/search/TypeRequestorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -53,7 +53,7 @@ public ITypeRequestor createRequestor(PossibleMatch possibleMatch, SearchPattern } else if (pattern instanceof PackageReferencePattern) { return new PackageReferenceSearchRequestor((PackageReferencePattern) pattern, requestor, possibleMatch.document.getParticipant()); } else if (pattern instanceof LocalVariablePattern) { - ILocalVariable localVar = (ILocalVariable) ReflectionUtils.getPrivateField(LocalVariablePattern.class, "localVariable", pattern); + ILocalVariable localVar = ReflectionUtils.getPrivateField(LocalVariablePattern.class, "localVariable", pattern); int start; try { start = localVar.getSourceRange().getOffset(); @@ -63,7 +63,7 @@ public ITypeRequestor createRequestor(PossibleMatch possibleMatch, SearchPattern } return new LocalVariableReferenceRequestor(localVar.getElementName(), localVar.getParent(), requestor, possibleMatch.document.getParticipant(), start); } else if (pattern instanceof OrPattern) { - SearchPattern[] patterns = (SearchPattern[]) ReflectionUtils.getPrivateField(OrPattern.class, "patterns", pattern); + SearchPattern[] patterns = ReflectionUtils.getPrivateField(OrPattern.class, "patterns", pattern); List requestors = new ArrayList<>(patterns.length); for (SearchPattern orPattern : patterns) { if (orPattern != null) { diff --git a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/debug/ConsoleLineTrackerTests.groovy b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/debug/ConsoleLineTrackerTests.groovy index 71312e6dd9..c8314810d3 100644 --- a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/debug/ConsoleLineTrackerTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/debug/ConsoleLineTrackerTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -72,7 +72,7 @@ final class ConsoleLineTrackerTests extends GroovyEclipseTestSuite { lineTracker.lineAppended(new Region(0, contents.length())) Assert.assertNotNull('Should have found a hyperlink', console.getLastLink()) FileLink link = (FileLink) console.getLastLink() - IFile file = (IFile) ReflectionUtils.getPrivateField(FileLink.class, 'fFile', link) + IFile file = ReflectionUtils.getPrivateField(FileLink.class, 'fFile', link) Assert.assertTrue('File should exist', file.isAccessible()) Assert.assertEquals('File name is wrong', 'Bar.groovy', file.getName()) } @@ -89,7 +89,7 @@ final class ConsoleLineTrackerTests extends GroovyEclipseTestSuite { Object file = ReflectionUtils.getPrivateField(FileLink.class, 'fFile', link) Assert.assertNull('File should be null since the selection is ambiguous', file) - IFile[] files = (IFile[]) ReflectionUtils.getPrivateField(AmbiguousFileLink.class, 'files', link) + IFile[] files = ReflectionUtils.getPrivateField(AmbiguousFileLink.class, 'files', link) Assert.assertEquals('Should have found 2 files', 2, files.length) Assert.assertEquals('File name is wrong', 'Baz.groovy', files[0].getName()) diff --git a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/ui/GroovyEditorTestSuite.groovy b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/ui/GroovyEditorTestSuite.groovy index 60516e8ba2..3fb36e1e63 100644 --- a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/ui/GroovyEditorTestSuite.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/ui/GroovyEditorTestSuite.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -164,7 +164,7 @@ abstract class GroovyEditorTestSuite extends GroovyEclipseTestSuite { protected void assertStatusLineText(String expected) { Object manager = ReflectionUtils.throwableExecutePrivateMethod(AbstractTextEditor.class, 'getStatusLineManager', new Class[0], editor, new Object[0]) - String actual = (String) ReflectionUtils.throwableGetPrivateField(manager.getClass(), 'message', manager) + String actual = ReflectionUtils.throwableGetPrivateField(manager.getClass(), 'message', manager) Assert.assertEquals(expected, actual) } } diff --git a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/wizards/NewGroovyTypeWizardTests.groovy b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/wizards/NewGroovyTypeWizardTests.groovy index 5aeecfc467..f6c9395b3f 100644 --- a/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/wizards/NewGroovyTypeWizardTests.groovy +++ b/ide-test/org.codehaus.groovy.eclipse.tests/src/org/codehaus/groovy/eclipse/test/wizards/NewGroovyTypeWizardTests.groovy @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -65,7 +65,7 @@ final class NewGroovyTypeWizardTests extends GroovyEclipseTestSuite { } private NewClassWizardPage clearModifiers(NewClassWizardPage wizardPage) { - SelectionButtonDialogFieldGroup group = (SelectionButtonDialogFieldGroup) ReflectionUtils.getPrivateField(NewTypeWizardPage, 'fAccMdfButtons', wizardPage) + SelectionButtonDialogFieldGroup group = ReflectionUtils.getPrivateField(NewTypeWizardPage, 'fAccMdfButtons', wizardPage) for (i in 0..5) { group.setSelection(i, false) } diff --git a/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/completions/GroovyJavaMethodCompletionProposal.java b/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/completions/GroovyJavaMethodCompletionProposal.java index 8ff7d17b0f..d25023c190 100644 --- a/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/completions/GroovyJavaMethodCompletionProposal.java +++ b/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/completions/GroovyJavaMethodCompletionProposal.java @@ -615,8 +615,8 @@ protected final boolean lastParamAcceptsClosure(char[][] parameterSignatures) { if (n > 0 && fInvocationContext.getCoreContext().isExtended()) { char[] lastType = Signature.getTypeErasure(parameterSignatures[n - 1]); if (Signature.getArrayCount(lastType) == 0) { - GroovyExtendedCompletionContext groovyContext = (GroovyExtendedCompletionContext) - ReflectionUtils.getPrivateField(InternalCompletionContext.class, "extendedContext", fInvocationContext.getCoreContext()); + GroovyExtendedCompletionContext groovyContext = ReflectionUtils.getPrivateField( + InternalCompletionContext.class, "extendedContext", fInvocationContext.getCoreContext()); return ClassHelper.isSAMType(groovyContext.toClassNode(lastType)); } @@ -686,7 +686,7 @@ public ReplacementPreferences(ProposalFormattingOptions opts, FormatterPrefs pre computer = key -> { boolean def = getDefaultOptions().get(key).matches(JavaCore.ENABLED + "|" + JavaCore.INSERT); - Boolean val = (Boolean) ReflectionUtils.executePrivateMethod(FormatterPrefs.class, "getCoreOption", + Boolean val = ReflectionUtils.executePrivateMethod(FormatterPrefs.class, "getCoreOption", new Class[] {IJavaProject.class, String.class, boolean.class}, prefs, new Object[] {project, key, def}); return val; }; diff --git a/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/creators/CategoryProposalCreator.java b/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/creators/CategoryProposalCreator.java index 0a5615c494..d081b76125 100644 --- a/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/creators/CategoryProposalCreator.java +++ b/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/creators/CategoryProposalCreator.java @@ -182,9 +182,9 @@ public IJavaCompletionProposal createJavaProposal(ContentAssistContext context, IJavaCompletionProposal javaProposal = super.createJavaProposal(context, javaContext); if (javaProposal instanceof LazyJavaCompletionProposal) { //ProposalInfo proposalInfo = ((LazyJavaCompletionProposal) javaProposal).getProposalInfo(); - ProposalInfo proposalInfo = (ProposalInfo) ReflectionUtils.executeNoArgPrivateMethod(LazyJavaCompletionProposal.class, "getProposalInfo", javaProposal); + ProposalInfo proposalInfo = ReflectionUtils.executePrivateMethod(LazyJavaCompletionProposal.class, "getProposalInfo", javaProposal); //CompletionProposal proposal = ((LazyJavaCompletionProposal) javaProposal).getProposal(); - CompletionProposal proposal = (CompletionProposal) ReflectionUtils.executeNoArgPrivateMethod(LazyJavaCompletionProposal.class, "getProposal", javaProposal); + CompletionProposal proposal = ReflectionUtils.executePrivateMethod(LazyJavaCompletionProposal.class, "getProposal", javaProposal); // reuse existing or create one to call some private methods final MethodProposalInfo methodProposalInfo = (proposalInfo instanceof MethodProposalInfo ? (MethodProposalInfo) proposalInfo : new MethodProposalInfo(javaContext.getProject(), proposal)); @@ -198,14 +198,14 @@ protected IMember resolveMember() throws JavaModelException { String methName = getMethod().getName(); String[] paramTypes = GroovyUtils.getParameterTypeSignatures(getMethod(), false); //Map typeVariables = methodProposalInfo.computeTypeVariables(type); - @SuppressWarnings("unchecked") Map typeVariables = (Map) ReflectionUtils. - throwableExecutePrivateMethod(MethodProposalInfo.class, "computeTypeVariables", new Class[] {IType.class}, methodProposalInfo, new Object[] {type}); + Map typeVariables = ReflectionUtils.throwableExecutePrivateMethod(MethodProposalInfo.class, "computeTypeVariables", + new Class[] {IType.class}, methodProposalInfo, new Object[] {type}); IMethod[] methods = type.getMethods(); for (int i = methods.length - 1; i >= 0; i -= 1) { if (!methName.equals(methods[i].getElementName())) continue; //boolean match = isSameMethodSignature(methName, paramTypes, false, methods[i], typeVariables, type); - Boolean match = (Boolean) ReflectionUtils.throwableExecutePrivateMethod(MethodProposalInfo.class, "isSameMethodSignature", + Boolean match = ReflectionUtils.throwableExecutePrivateMethod(MethodProposalInfo.class, "isSameMethodSignature", new Class [] {String.class, String[].class, boolean.class, IMethod.class, Map.class, IType.class}, methodProposalInfo, new Object[] {methName, paramTypes, Boolean.FALSE, methods[i], typeVariables, type }); if (Boolean.TRUE.equals(match)) { diff --git a/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/factories/AnnotationCollectorTypeCompletionProcessorFactory.java b/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/factories/AnnotationCollectorTypeCompletionProcessorFactory.java index 0c8bdae1bc..30e57e5801 100644 --- a/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/factories/AnnotationCollectorTypeCompletionProcessorFactory.java +++ b/ide/org.codehaus.groovy.eclipse.codeassist.completion/src/org/codehaus/groovy/eclipse/codeassist/factories/AnnotationCollectorTypeCompletionProcessorFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -63,8 +63,7 @@ public List generateProposals(IProgressMonitor monitor) { it.remove(); } else { // change the displayed icon from 'C' to '@' - GroovyCompletionProposal gcp = (GroovyCompletionProposal) ReflectionUtils - .getPrivateField(LazyJavaCompletionProposal.class, "fProposal", proposal); + GroovyCompletionProposal gcp = ReflectionUtils.getPrivateField(LazyJavaCompletionProposal.class, "fProposal", proposal); gcp.setFlags(gcp.getFlags() | 0x00002000 /*aka Modifier.ANNOTATION*/); } } diff --git a/ide/org.codehaus.groovy.eclipse.core/src/org/codehaus/groovy/eclipse/core/builder/GroovyNameLookup.java b/ide/org.codehaus.groovy.eclipse.core/src/org/codehaus/groovy/eclipse/core/builder/GroovyNameLookup.java index bab94649d3..e89cfc1733 100644 --- a/ide/org.codehaus.groovy.eclipse.core/src/org/codehaus/groovy/eclipse/core/builder/GroovyNameLookup.java +++ b/ide/org.codehaus.groovy.eclipse.core/src/org/codehaus/groovy/eclipse/core/builder/GroovyNameLookup.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,7 +18,6 @@ import java.util.HashMap; import java.util.Map; -import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IPackageFragment; @@ -39,13 +38,12 @@ */ public class GroovyNameLookup extends NameLookup { - @SuppressWarnings("unchecked") public GroovyNameLookup(NameLookup other) { this(new IPackageFragmentRoot[0], new HashtableOfArrayToObject(), new ICompilationUnit[0], new HashMap()); - this.packageFragmentRoots = (IPackageFragmentRoot[]) ReflectionUtils.getPrivateField(NameLookup.class, "packageFragmentRoots", other); - this.packageFragments = (HashtableOfArrayToObject) ReflectionUtils.getPrivateField(NameLookup.class, "packageFragments", other); - this.typesInWorkingCopies = (HashMap) ReflectionUtils.getPrivateField(NameLookup.class, "typesInWorkingCopies", other); - this.rootToResolvedEntries = (Map) ReflectionUtils.getPrivateField(NameLookup.class, "rootToResolvedEntries", other); + this.packageFragmentRoots = ReflectionUtils.getPrivateField(NameLookup.class, "packageFragmentRoots", other); + this.packageFragments = ReflectionUtils.getPrivateField(NameLookup.class, "packageFragments", other); + this.typesInWorkingCopies = ReflectionUtils.getPrivateField(NameLookup.class, "typesInWorkingCopies", other); + this.rootToResolvedEntries = ReflectionUtils.getPrivateField(NameLookup.class, "rootToResolvedEntries", other); } public GroovyNameLookup(IPackageFragmentRoot[] packageFragmentRoots, HashtableOfArrayToObject packageFragments, ICompilationUnit[] workingCopies, Map rootToResolvedEntries) { diff --git a/ide/org.codehaus.groovy.eclipse.core/src/org/codehaus/groovy/eclipse/core/compiler/GroovySnippetParser.java b/ide/org.codehaus.groovy.eclipse.core/src/org/codehaus/groovy/eclipse/core/compiler/GroovySnippetParser.java index b795d63bac..c3d2748577 100644 --- a/ide/org.codehaus.groovy.eclipse.core/src/org/codehaus/groovy/eclipse/core/compiler/GroovySnippetParser.java +++ b/ide/org.codehaus.groovy.eclipse.core/src/org/codehaus/groovy/eclipse/core/compiler/GroovySnippetParser.java @@ -80,10 +80,10 @@ public ModuleNode parse(CharSequence source) { public GroovySourceAST parseForCST(CharSequence source) { SourceUnit sourceUnit = dietParse(source).getSourceUnit(); - ParserPlugin parserPlugin = (ParserPlugin) ReflectionUtils.getPrivateField(SourceUnit.class, "parserPlugin", sourceUnit); + ParserPlugin parserPlugin = ReflectionUtils.getPrivateField(SourceUnit.class, "parserPlugin", sourceUnit); if (parserPlugin instanceof AntlrParserPlugin) { // TODO: This field is nulled out at the end of AntlrParserPlugin.buildAST - return (GroovySourceAST) ReflectionUtils.getPrivateField(AntlrParserPlugin.class, "ast", parserPlugin); + return ReflectionUtils.getPrivateField(AntlrParserPlugin.class, "ast", parserPlugin); } return null; } diff --git a/ide/org.codehaus.groovy.eclipse.refactoring/src/org/codehaus/groovy/eclipse/refactoring/core/extract/ExtractGroovyConstantRefactoring.java b/ide/org.codehaus.groovy.eclipse.refactoring/src/org/codehaus/groovy/eclipse/refactoring/core/extract/ExtractGroovyConstantRefactoring.java index 1a224c93a2..dd30189119 100644 --- a/ide/org.codehaus.groovy.eclipse.refactoring/src/org/codehaus/groovy/eclipse/refactoring/core/extract/ExtractGroovyConstantRefactoring.java +++ b/ide/org.codehaus.groovy.eclipse.refactoring/src/org/codehaus/groovy/eclipse/refactoring/core/extract/ExtractGroovyConstantRefactoring.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -170,7 +170,7 @@ private int expandSelection(int s, int l) { } private CompilationUnitChange getChange() { - return (CompilationUnitChange) ReflectionUtils.getPrivateField(ExtractConstantRefactoring.class, "fChange", this); + return ReflectionUtils.getPrivateField(ExtractConstantRefactoring.class, "fChange", this); } private void setChange(CompilationUnitChange change) { @@ -648,24 +648,21 @@ public String getConstantName() { private GroovyCompilationUnit getCu() { if (unit == null) { - unit = - (GroovyCompilationUnit) ReflectionUtils.getPrivateField(ExtractConstantRefactoring.class, "fCu", this); + unit = ReflectionUtils.getPrivateField(ExtractConstantRefactoring.class, "fCu", this); } return unit; } private int getSelectionStart() { if (start == -1) { - start = - (Integer) ReflectionUtils.getPrivateField(ExtractConstantRefactoring.class, "fSelectionStart", this); + start = (Integer) ReflectionUtils.getPrivateField(ExtractConstantRefactoring.class, "fSelectionStart", this); } return start; } private int getSelectionLength() { if (length == -1) { - length = - (Integer) ReflectionUtils.getPrivateField(ExtractConstantRefactoring.class, "fSelectionLength", this); + length = (Integer) ReflectionUtils.getPrivateField(ExtractConstantRefactoring.class, "fSelectionLength", this); } return length; } diff --git a/ide/org.codehaus.groovy.eclipse.refactoring/src/org/codehaus/groovy/eclipse/refactoring/core/rename/renameLocal/RenameLocalGroovyVariableContribution.java b/ide/org.codehaus.groovy.eclipse.refactoring/src/org/codehaus/groovy/eclipse/refactoring/core/rename/renameLocal/RenameLocalGroovyVariableContribution.java index 072e165ab6..cfdbb6d53f 100644 --- a/ide/org.codehaus.groovy.eclipse.refactoring/src/org/codehaus/groovy/eclipse/refactoring/core/rename/renameLocal/RenameLocalGroovyVariableContribution.java +++ b/ide/org.codehaus.groovy.eclipse.refactoring/src/org/codehaus/groovy/eclipse/refactoring/core/rename/renameLocal/RenameLocalGroovyVariableContribution.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -41,8 +41,8 @@ public RefactoringDescriptor createDescriptor(String id, String project, String @Override public Refactoring createRefactoring(JavaRefactoringDescriptor descriptor, RefactoringStatus status) throws CoreException { if (descriptor instanceof RenameJavaElementDescriptor) { - IJavaElement elt = (IJavaElement) ReflectionUtils.getPrivateField(RenameJavaElementDescriptor.class, "fJavaElement", descriptor); - String newName = (String) ReflectionUtils.getPrivateField(RenameJavaElementDescriptor.class, "fName", descriptor); + IJavaElement elt = ReflectionUtils.getPrivateField(RenameJavaElementDescriptor.class, "fJavaElement", descriptor); + String newName = ReflectionUtils.getPrivateField(RenameJavaElementDescriptor.class, "fName", descriptor); if (elt instanceof ILocalVariable && newName != null) { ILocalVariable var = (ILocalVariable) elt; return new RenameRefactoring(new GroovyRenameLocalVariableProcessor(var, newName, status)); diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/adapters/ClassFileEditorAdapterFactory.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/adapters/ClassFileEditorAdapterFactory.java index 3aad066541..5a1882d30c 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/adapters/ClassFileEditorAdapterFactory.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/adapters/ClassFileEditorAdapterFactory.java @@ -47,8 +47,8 @@ public T getAdapter(Object adaptable, Class adapterType) { CompilationUnit unit = SharedASTProvider.getAST(root, SharedASTProvider.WAIT_YES, null); if (unit.getClass().getName().equals("org.codehaus.jdt.groovy.core.dom.GroovyCompilationUnit")) { // TODO: Is there a better way to get from GroovyCompilationUnit to GroovyCompilationUnitDeclaration? - Object resolver = ReflectionUtils.executeNoArgPrivateMethod(org.eclipse.jdt.core.dom.AST.class, "getBindingResolver", unit.getAST()); - CompilationUnitScope scope = (CompilationUnitScope) ReflectionUtils.executeNoArgPrivateMethod(resolver.getClass(), "scope", resolver); + Object resolver = ReflectionUtils.executePrivateMethod(org.eclipse.jdt.core.dom.AST.class, "getBindingResolver", unit.getAST()); + CompilationUnitScope scope = ReflectionUtils.executePrivateMethod(resolver.getClass(), "scope", resolver); ModuleNode moduleNode = ((GroovyCompilationUnitDeclaration) scope.referenceContext).getModuleNode(); if (adapterType.equals(ModuleNode.class)) { diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/debug/ui/EnsureJUnitFont.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/debug/ui/EnsureJUnitFont.java index 3def8dfe83..d0ef91c188 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/debug/ui/EnsureJUnitFont.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/debug/ui/EnsureJUnitFont.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -80,7 +80,7 @@ private boolean isMonospace() { private void internalSetMonospaceFont(boolean isMonospace, TestRunnerViewPart view) { FailureTrace trace = view.getFailureTrace(); - Composite widget = (Composite) ReflectionUtils.getPrivateField(FailureTrace.class, "fTable", trace); + Composite widget = ReflectionUtils.getPrivateField(FailureTrace.class, "fTable", trace); if (isMonospace) { widget.setFont(JFaceResources.getTextFont()); } else { diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/debug/ui/GroovyBreakpointRulerActionDelegate.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/debug/ui/GroovyBreakpointRulerActionDelegate.java index 624e50972c..69683dbe43 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/debug/ui/GroovyBreakpointRulerActionDelegate.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/debug/ui/GroovyBreakpointRulerActionDelegate.java @@ -66,7 +66,7 @@ public void dispose() { //-------------------------------------------------------------------------- protected IEditorPart getEditorPart() { - return (IEditorPart) ReflectionUtils.getPrivateField(RulerToggleBreakpointActionDelegate.class, "fEditor", this); + return ReflectionUtils.getPrivateField(RulerToggleBreakpointActionDelegate.class, "fEditor", this); } protected IProject getProject(IEditorInput editorInput) { diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyAutoIndentStrategy.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyAutoIndentStrategy.java index f47aeda9cd..86a785ad3a 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyAutoIndentStrategy.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyAutoIndentStrategy.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ import org.codehaus.groovy.eclipse.GroovyPlugin; import org.codehaus.groovy.eclipse.refactoring.formatter.GroovyIndentationService; -import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.groovy.core.util.ReflectionUtils; import org.eclipse.jdt.internal.ui.text.java.JavaAutoIndentStrategy; import org.eclipse.jface.text.BadLocationException; @@ -39,9 +38,9 @@ public class GroovyAutoIndentStrategy extends AbstractAutoEditStrategy { public GroovyAutoIndentStrategy(JavaAutoIndentStrategy javaStrategy) { this.javaStrategy = javaStrategy; - ReflectionUtils.executeNoArgPrivateMethod(JavaAutoIndentStrategy.class, "clearCachedValues", javaStrategy); + ReflectionUtils.executePrivateMethod(JavaAutoIndentStrategy.class, "clearCachedValues", javaStrategy); this.closeBraces = (Boolean) ReflectionUtils.getPrivateField(JavaAutoIndentStrategy.class, "fCloseBrace", javaStrategy); - this.indentService = GroovyIndentationService.get((IJavaProject) ReflectionUtils.getPrivateField(JavaAutoIndentStrategy.class, "fProject", javaStrategy)); + this.indentService = GroovyIndentationService.get(ReflectionUtils.getPrivateField(JavaAutoIndentStrategy.class, "fProject", javaStrategy)); } @Override diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyAwareFoldingStructureProvider.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyAwareFoldingStructureProvider.java index 090da1a730..6aa2a120ce 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyAwareFoldingStructureProvider.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyAwareFoldingStructureProvider.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -168,6 +168,6 @@ protected final boolean isScriptMethodElement(IRegion region) { } protected static IDocument getDocument(FoldingStructureComputationContext context) { - return (IDocument) ReflectionUtils.executeNoArgPrivateMethod(context.getClass(), "getDocument", context); + return ReflectionUtils.executePrivateMethod(context.getClass(), "getDocument", context); } } diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyConfiguration.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyConfiguration.java index 84b875e627..2a33da82cd 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyConfiguration.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -116,7 +116,7 @@ public String[] getConfiguredContentTypes(ISourceViewer sourceViewer) { }; } - @Override @SuppressWarnings("unchecked") + @Override public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { ContentAssistant assistant = (ContentAssistant) super.getContentAssistant(sourceViewer); @@ -125,8 +125,7 @@ public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) { // retain only Groovy-approved completion proposal categories IContentAssistProcessor processor = assistant.getContentAssistProcessor(IDocument.DEFAULT_CONTENT_TYPE); - List categories = (List) - ReflectionUtils.getPrivateField(ContentAssistProcessor.class, "fCategories", processor); + List categories = ReflectionUtils.getPrivateField(ContentAssistProcessor.class, "fCategories", processor); List newCategories = new ArrayList<>(); for (CompletionProposalCategory category : categories) { if (GROOVY_CONTENT_ASSIST.matcher(category.getId()).matches()) { diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyEditor.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyEditor.java index 59ca980482..c27917efc1 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyEditor.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/GroovyEditor.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -68,7 +68,6 @@ import org.eclipse.jdt.internal.ui.javaeditor.JavaEditor; import org.eclipse.jdt.internal.ui.javaeditor.JavaOutlinePage; import org.eclipse.jdt.internal.ui.javaeditor.JavaSourceViewer; -import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.SelectionHistory; import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.StructureSelectionAction; import org.eclipse.jdt.internal.ui.text.JavaHeuristicScanner; import org.eclipse.jdt.internal.ui.text.JavaWordFinder; @@ -860,11 +859,9 @@ private void unsetJavaBreakpointUpdater() { if (model instanceof AbstractMarkerAnnotationModel) { if (ReflectionUtils.getPrivateField(AbstractMarkerAnnotationModel.class, "fMarkerUpdaterSpecifications", model) == null) { // force instantiation of the extension points - ReflectionUtils.executeNoArgPrivateMethod(AbstractMarkerAnnotationModel.class, "installMarkerUpdaters", model); + ReflectionUtils.executePrivateMethod(AbstractMarkerAnnotationModel.class, "installMarkerUpdaters", model); } - @SuppressWarnings("unchecked") - List updaterSpecs = (List) - ReflectionUtils.getPrivateField(AbstractMarkerAnnotationModel.class, "fMarkerUpdaterSpecifications", model); + List updaterSpecs = ReflectionUtils.getPrivateField(AbstractMarkerAnnotationModel.class, "fMarkerUpdaterSpecifications", model); // remove the marker updater for Java breakpoints; the Groovy one will be used instead for (Iterator specIter = updaterSpecs.iterator(); specIter.hasNext();) { IConfigurationElement spec = specIter.next(); @@ -1035,8 +1032,7 @@ protected void createActions() { markAsStateDependentAction("IndentOnTab", true); // selection history actions - ExpandSelectionAction selectionAction = new ExpandSelectionAction(this, - (SelectionHistory) ReflectionUtils.getPrivateField(JavaEditor.class, "fSelectionHistory", this)); + ExpandSelectionAction selectionAction = new ExpandSelectionAction(this, ReflectionUtils.getPrivateField(JavaEditor.class, "fSelectionHistory", this)); selectionAction.setActionDefinitionId(IJavaEditorActionDefinitionIds.SELECT_ENCLOSING); setAction(StructureSelectionAction.ENCLOSING, selectionAction); setAction(StructureSelectionAction.PREVIOUS, null); @@ -1047,8 +1043,8 @@ protected void createActions() { ISurroundWithFactory surroundWithFactory = (ISurroundWithFactory) Platform.getAdapterManager() .loadAdapter(this, "org.codehaus.groovy.eclipse.quickfix.templates.SurroundWithAdapterFactory"); if (surroundWithFactory != null) { - CompositeActionGroup compositActions = (CompositeActionGroup) ReflectionUtils.getPrivateField(CompilationUnitEditor.class, "fContextMenuGroup", this); - ActionGroup[] groups = (ActionGroup[]) ReflectionUtils.getPrivateField(CompositeActionGroup.class, "fGroups", compositActions); + CompositeActionGroup compositActions = ReflectionUtils.getPrivateField(CompilationUnitEditor.class, "fContextMenuGroup", this); + ActionGroup[] groups = ReflectionUtils.getPrivateField(CompositeActionGroup.class, "fGroups", compositActions); boolean found = false; ActionGroup surroundWithGroup = surroundWithFactory.createSurrundWithGroup(this, ITextEditorActionConstants.GROUP_EDIT); for (int i = 0, n = groups.length; i < n; i += 1) { @@ -1063,7 +1059,7 @@ protected void createActions() { } found = false; - groups = (ActionGroup[]) ReflectionUtils.getPrivateField(CompositeActionGroup.class, "fGroups", fActionGroups); + groups = ReflectionUtils.getPrivateField(CompositeActionGroup.class, "fGroups", fActionGroups); for (int i = 0, n = groups.length; i < n; i += 1) { if (groups[i] instanceof SurroundWithActionGroup) { found = true; @@ -1171,7 +1167,7 @@ protected void updateSourceActions() { ReflectionUtils.setPrivateField(GenerateActionGroup.class, "fOrganizeImports", group, organizeGroovyImportsAction); // disable Clean Ups... - AllCleanUpsAction acua = (AllCleanUpsAction) ReflectionUtils.getPrivateField(GenerateActionGroup.class, "fCleanUp", group); + AllCleanUpsAction acua = ReflectionUtils.getPrivateField(GenerateActionGroup.class, "fCleanUp", group); acua.setEnabled(false); } @@ -1240,7 +1236,7 @@ protected final void removeRefactoringAction(String actionFieldName) { protected final void replaceRefactoringAction(String actionFieldName, SelectionDispatchAction newAction) { RefactorActionGroup group = getRefactorActionGroup(); - SelectionDispatchAction action = (SelectionDispatchAction) ReflectionUtils.getPrivateField(RefactorActionGroup.class, actionFieldName, group); + SelectionDispatchAction action = ReflectionUtils.getPrivateField(RefactorActionGroup.class, actionFieldName, group); if (action != null) { getSite().getSelectionProvider().removeSelectionChangedListener(action); } @@ -1328,7 +1324,7 @@ protected IRegion findMarkOccurrencesRegion(IDocument document, int offset) { } protected Job fOccurrencesFinderJob_get() throws Exception { - return (Job) ReflectionUtils.throwableGetPrivateField(JavaEditor.class, "fOccurrencesFinderJob", this); + return ReflectionUtils.throwableGetPrivateField(JavaEditor.class, "fOccurrencesFinderJob", this); } protected boolean fMarkOccurrenceAnnotations_get() throws Exception { @@ -1336,7 +1332,7 @@ protected boolean fMarkOccurrenceAnnotations_get() throws Exception { } protected IRegion fMarkOccurrenceTargetRegion_get() throws Exception { - return (IRegion) ReflectionUtils.throwableGetPrivateField(JavaEditor.class, "fMarkOccurrenceTargetRegion", this); + return ReflectionUtils.throwableGetPrivateField(JavaEditor.class, "fMarkOccurrenceTargetRegion", this); } protected void fMarkOccurrenceTargetRegion_set(IRegion r) throws Exception { diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/highlighting/GroovySemanticReconciler.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/highlighting/GroovySemanticReconciler.java index 791c434bac..fbe055200f 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/highlighting/GroovySemanticReconciler.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/editor/highlighting/GroovySemanticReconciler.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -307,10 +307,9 @@ private boolean update(IProgressMonitor monitor, int units) { return monitor.isCanceled(); } - @SuppressWarnings("unchecked") private List getHighlightedPositions() { // NOTE: Be very careful with this; fPositions is often accessed synchronously! - return (List) ReflectionUtils.getPrivateField(SemanticHighlightingPresenter.class, "fPositions", presenter); + return ReflectionUtils.getPrivateField(SemanticHighlightingPresenter.class, "fPositions", presenter); } private Position newHighlightedPosition(HighlightedTypedPosition pos) { @@ -405,7 +404,7 @@ private boolean isSameStyle(Position a, Position b) { private TextAttribute getTextAttribute(Object highlightingStyle) { // return highlightingStyle.getTextAttribute(); - return (TextAttribute) ReflectionUtils.executeNoArgPrivateMethod(highlightingStyle.getClass(), "getTextAttribute", highlightingStyle); + return ReflectionUtils.executePrivateMethod(highlightingStyle.getClass(), "getTextAttribute", highlightingStyle); } /** diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/launchers/GroovyShellLauncherTab.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/launchers/GroovyShellLauncherTab.java index 6f048dd5e0..be872aca34 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/launchers/GroovyShellLauncherTab.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/launchers/GroovyShellLauncherTab.java @@ -45,15 +45,13 @@ protected void createMainTypeEditor(Composite parent, String text) { super.createMainTypeEditor(parent, text); fMainText.getParent().setVisible(false); fMainText.setText("org.codehaus.groovy.tools.shell.Main"); - Button fSearchButton = (Button) ReflectionUtils.getPrivateField(SharedJavaMainTab.class, "fSearchButton", this); + Button fSearchButton = ReflectionUtils.getPrivateField(SharedJavaMainTab.class, "fSearchButton", this); fSearchButton.setVisible(false); - Button fSearchExternalJarsCheckButton = (Button) ReflectionUtils.getPrivateField(JavaMainTab.class, - "fSearchExternalJarsCheckButton", this); + Button fSearchExternalJarsCheckButton = ReflectionUtils.getPrivateField(JavaMainTab.class, "fSearchExternalJarsCheckButton", this); fSearchExternalJarsCheckButton.setVisible(false); - Button fConsiderInheritedMainButton = (Button) ReflectionUtils.getPrivateField(JavaMainTab.class, - "fConsiderInheritedMainButton", this); + Button fConsiderInheritedMainButton = ReflectionUtils.getPrivateField(JavaMainTab.class, "fConsiderInheritedMainButton", this); fConsiderInheritedMainButton.setVisible(false); - Button fStopInMainCheckButton = (Button) ReflectionUtils.getPrivateField(JavaMainTab.class, "fStopInMainCheckButton", this); + Button fStopInMainCheckButton = ReflectionUtils.getPrivateField(JavaMainTab.class, "fStopInMainCheckButton", this); fStopInMainCheckButton.setVisible(false); } @@ -72,24 +70,16 @@ public void initializeFrom(ILaunchConfiguration config) { } fProjText.setText(projectName); - ReflectionUtils.executePrivateMethod(JavaLaunchTab.class, "setCurrentLaunchConfiguration", - new Class[] { ILaunchConfiguration.class }, this, new Object[] { config }); + ReflectionUtils.executePrivateMethod(JavaLaunchTab.class, "setCurrentLaunchConfiguration", new Class[] {ILaunchConfiguration.class}, this, new Object[] {config}); } - /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getName() - */ @Override public String getName() { - return "Groovy Shell"; //$NON-NLS-1$ + return "Groovy Shell"; } - /** - * @see org.eclipse.debug.ui.ILaunchConfigurationTab#getImage() - */ @Override public Image getImage() { return JavaUI.getSharedImages().getImage(ISharedImages.IMG_OBJS_CLASS); } - } diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/AddImportOnSelectionAction.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/AddImportOnSelectionAction.java index b5062a403e..cfd3452d1f 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/AddImportOnSelectionAction.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/AddImportOnSelectionAction.java @@ -253,7 +253,7 @@ private TypeNameMatch findCandidateTypes(String typeName, int typeStart, IProgre private int startOffset(ASTNode node, ASTNodeFinder nodeFinder) throws CoreException { int start = node.getStart(); if (node.getEnd() < 1) { - Region nodeRegion = (Region) ReflectionUtils.getPrivateField(ASTNodeFinder.class, "sloc", nodeFinder); + Region nodeRegion = ReflectionUtils.getPrivateField(ASTNodeFinder.class, "sloc", nodeFinder); if (nodeRegion != null) { start = nodeRegion.getOffset(); // may be approximate while (!Character.isJavaIdentifierStart(compilationUnit.getSource().charAt(start))) { @@ -267,7 +267,7 @@ private int startOffset(ASTNode node, ASTNodeFinder nodeFinder) throws CoreExcep private int endOffset(ASTNode node, ASTNodeFinder nodeFinder) throws CoreException { int end = node.getEnd(); if (end < 1) { - Region nodeRegion = (Region) ReflectionUtils.getPrivateField(ASTNodeFinder.class, "sloc", nodeFinder); + Region nodeRegion = ReflectionUtils.getPrivateField(ASTNodeFinder.class, "sloc", nodeFinder); if (nodeRegion != null) { end = nodeRegion.getEnd(); // may be approximate while (end > 0 && !Character.isJavaIdentifierPart(compilationUnit.getSource().charAt(end - 1))) { diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/AddImportOnSelectionAdapter.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/AddImportOnSelectionAdapter.java index ff3f6829f6..91a9eeb9a7 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/AddImportOnSelectionAdapter.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/AddImportOnSelectionAdapter.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -105,7 +105,7 @@ private ICompilationUnit getCompilationUnit() { } private CompilationUnitEditor getCompilationUnitEditor() { - CompilationUnitEditor editor = (CompilationUnitEditor) ReflectionUtils.getPrivateField( + CompilationUnitEditor editor = ReflectionUtils.getPrivateField( org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction.class, "fEditor", this); return editor; } @@ -119,7 +119,7 @@ private IChooseImportQuery newChooseImportQuery(Shell shell) { } private IEditingSupport newEditingSupport(ITextSelection textSelection, IChooseImportQuery typeQuery) { - return (IEditingSupport) ReflectionUtils.executePrivateMethod( + return ReflectionUtils.executePrivateMethod( org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction.class, "createViewerHelper", new Class[] {ITextSelection.class, SELECT_TYPE_QUERY}, this, new Object[] {textSelection, typeQuery}); // return new IEditingSupport() { diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/GroovyRenameLinkedMode.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/GroovyRenameLinkedMode.java index 93627d3494..676ccf7d1f 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/GroovyRenameLinkedMode.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/GroovyRenameLinkedMode.java @@ -1,5 +1,5 @@ /* - * Copyright 2009-2017 the original author or authors. + * Copyright 2009-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -227,7 +227,7 @@ private void setLinkedPositionGroup(LinkedPositionGroup group) { } private IEditingSupport getFocusEditingSupport() { - return (IEditingSupport) ReflectionUtils.getPrivateField(RenameLinkedMode.class, "fFocusEditingSupport", this); + return ReflectionUtils.getPrivateField(RenameLinkedMode.class, "fFocusEditingSupport", this); } private boolean getShowPreview() { @@ -235,11 +235,11 @@ private boolean getShowPreview() { } private IJavaElement getJavaElement() { - return (IJavaElement) ReflectionUtils.getPrivateField(RenameLinkedMode.class, "fJavaElement", this); + return ReflectionUtils.getPrivateField(RenameLinkedMode.class, "fJavaElement", this); } private static RenameLinkedMode getMyActiveLinkedMode() { - return (RenameLinkedMode) ReflectionUtils.getPrivateField(RenameLinkedMode.class, "fgActiveLinkedMode", null); + return ReflectionUtils.getPrivateField(RenameLinkedMode.class, "fgActiveLinkedMode", null); } private void setShowPreview(boolean show) { @@ -267,11 +267,11 @@ private void setActiveLinkedMode(RenameLinkedMode active) { } private void doOpenSecondaryPopup() { - ReflectionUtils.executeNoArgPrivateMethod(RenameLinkedMode.class, "openSecondaryPopup", this); + ReflectionUtils.executePrivateMethod(RenameLinkedMode.class, "openSecondaryPopup", this); } private void doLinkedModeLeft() { - ReflectionUtils.executeNoArgPrivateMethod(RenameLinkedMode.class, "linkedModeLeft", this); + ReflectionUtils.executePrivateMethod(RenameLinkedMode.class, "linkedModeLeft", this); } private void doDoRename(boolean showPreview) { diff --git a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/OrganizeGroovyImportsAction.java b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/OrganizeGroovyImportsAction.java index fd50d0693e..fd57350021 100644 --- a/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/OrganizeGroovyImportsAction.java +++ b/ide/org.codehaus.groovy.eclipse.ui/src/org/codehaus/groovy/eclipse/refactoring/actions/OrganizeGroovyImportsAction.java @@ -90,11 +90,11 @@ public void run(IStructuredSelection selection) { } protected JavaEditor getEditor() { - return (JavaEditor) ReflectionUtils.getPrivateField(OrganizeImportsAction.class, "fEditor", this); + return ReflectionUtils.getPrivateField(OrganizeImportsAction.class, "fEditor", this); } protected MultiOrganizeImportAction getDelegate() { - MultiOrganizeImportAction delegate = (MultiOrganizeImportAction) ReflectionUtils.getPrivateField(OrganizeImportsAction.class, "fCleanUpDelegate", this); + MultiOrganizeImportAction delegate = ReflectionUtils.getPrivateField(OrganizeImportsAction.class, "fCleanUpDelegate", this); // override the final field's MultiOrganizeImportAction with our import clean-up MultiOrganizeImportAction override = new MultiOrganizeImportAction(getSite()) { @Override