public static boolean isTagValueGetter(final JavaMethod method) { if (!isGetter(method)) { return false; } if (hasTagValueAnnotation(method)) { return true; } if ("getValue".equals(method.getName())) { if (method.getAnnotation(SubTag.class) != null) return false; if (method.getAnnotation(SubTagList.class) != null) return false; if (method.getAnnotation(Convert.class) != null || method.getAnnotation(Resolve.class) != null) { return !ReflectionUtil.isAssignable(GenericDomValue.class, method.getReturnType()); } if (ReflectionUtil.isAssignable(DomElement.class, method.getReturnType())) return false; return true; } return false; }
protected boolean shouldBeShown(final Type type) { final Map<Class, Boolean> hiders = DomUtil.getFile(getDomElement()).getUserData(TREE_NODES_HIDERS_KEY); if (type == null || hiders == null || hiders.size() == 0) return true; final Class aClass = ReflectionUtil.getRawType(type); List<Class> allParents = new ArrayList<Class>(); for (Map.Entry<Class, Boolean> entry : hiders.entrySet()) { if (entry.getKey().isAssignableFrom(aClass)) { allParents.add(entry.getKey()); } } if (allParents.size() == 0) return false; Collections.sort(allParents, INHERITORS_COMPARATOR); return hiders.get(allParents.get(0)).booleanValue(); }
private boolean isLocationInExpandControl(final TreePath path, final int x, final int y) { final TreeUI ui = getUI(); if (!(ui instanceof BasicTreeUI)) return false; try { Class aClass = ui.getClass(); while (BasicTreeUI.class.isAssignableFrom(aClass) && !BasicTreeUI.class.equals(aClass)) { aClass = aClass.getSuperclass(); } final Method method = ReflectionUtil.getDeclaredMethod(aClass, "isLocationInExpandControl", TreePath.class, int.class, int.class); if (method != null) { return (Boolean)method.invoke(ui, path, x, y); } } catch (Throwable ignore) { } return false; }
private static void clearAntStaticCache(final Class helperClass) { //if (++ourClearAttemptCount > 1000) { // allow not more than 1000 helpers cached inside ant // ourClearAttemptCount = 0; //} //else { // return; //} // for ant 1.7, there is a dedicated method for cache clearing try { final Method method = helperClass.getDeclaredMethod("clearCache"); method.invoke(null); } catch (Throwable e) { try { // assume it is older version of ant Map helpersCollection = ReflectionUtil.getField(helperClass, null, null, "helpers"); helpersCollection.clear(); } catch (Throwable _e) { // ignore. } } }
@Override public boolean isDumbAware() { if (myDumbAware != null) { return myDumbAware; } boolean dumbAware = super.isDumbAware(); if (dumbAware) { myDumbAware = Boolean.TRUE; } else { if (myDumbAware == null) { Class<?> declaringClass = ReflectionUtil.getMethodDeclaringClass(getClass(), "update", AnActionEvent.class); myDumbAware = AnAction.class.equals(declaringClass) || ActionGroup.class.equals(declaringClass); } } return myDumbAware; }
@Nullable private static Object getPropertyValue(Object componentInstance, String propertyName) { final Class<? extends Object> componentInstanceClass = componentInstance.getClass(); Object propertyValue = ReflectionUtil.getField(componentInstanceClass, componentInstance, null, propertyName); if (propertyValue == null) { Method method = ReflectionUtil.getMethod(componentInstanceClass, "get" + StringUtil.capitalize(propertyName)); if (method == null) { method = ReflectionUtil.getMethod(componentInstanceClass, "is" + StringUtil.capitalize(propertyName)); } if (method != null) { try { propertyValue = method.invoke(componentInstance); } catch (Exception ignored) { } } } return propertyValue; }
void fillTable() { Class<?> clazz0 = myComponent.getClass(); Class<?> clazz = clazz0.isAnonymousClass() ? clazz0.getSuperclass() : clazz0; myProperties.add(new PropertyBean("class", clazz.getName())); for (String name: PROPERTIES) { String propertyName = ObjectUtils.notNull(StringUtil.getPropertyName(name), name); Object propertyValue; try { try { //noinspection ConstantConditions propertyValue = ReflectionUtil.findMethod(Arrays.asList(clazz.getMethods()), name).invoke(myComponent); } catch (Exception e) { propertyValue = ReflectionUtil.findField(clazz, null, name).get(myComponent); } myProperties.add(new PropertyBean(propertyName, propertyValue)); } catch (Exception ignored) { } } Object addedAt = myComponent instanceof JComponent ? ((JComponent)myComponent).getClientProperty("uiInspector.addedAt") : null; myProperties.add(new PropertyBean("added-at", addedAt)); }
private static void fixGtkPopupStyle() { if (!UIUtil.isUnderGTKLookAndFeel()) return; final SynthStyleFactory original = SynthLookAndFeel.getStyleFactory(); SynthLookAndFeel.setStyleFactory(new SynthStyleFactory() { @Override public SynthStyle getStyle(final JComponent c, final Region id) { final SynthStyle style = original.getStyle(c, id); if (id == Region.POPUP_MENU) { final Integer x = ReflectionUtil.getField(style.getClass(), style, int.class, "xThickness"); if (x != null && x == 0) { // workaround for Sun bug #6636964 ReflectionUtil.setField(style.getClass(), style, int.class, "xThickness", 1); ReflectionUtil.setField(style.getClass(), style, int.class, "yThickness", 3); } } return style; } }); new JBPopupMenu(); // invokes updateUI() -> updateStyle() SynthLookAndFeel.setStyleFactory(original); }
private static void doConvert(Object object, String prefix, Map<String, String> result) throws IllegalAccessException { for (Field each : ReflectionUtil.collectFields(object.getClass())) { Class<?> type = each.getType(); if (shouldSkip(type)) continue; each.setAccessible(true); Object value = each.get(object); if (value != null) { String name = prefix + each.getName(); String sValue = String.valueOf(value); if (!isNativeToString(sValue, value)) { result.put(name, sValue); } Package pack = type.getPackage(); if (pack != null && Model.class.getPackage().getName().equals(pack.getName())) { doConvert(value, name + ".", result); } } } }
private static void fixStickyAlt(AWTEvent e) { if (Registry.is("actionSystem.win.suppressAlt.new")) { if (UIUtil.isUnderWindowsLookAndFeel() && e instanceof InputEvent && (((InputEvent)e).getModifiers() & (InputEvent.ALT_MASK | InputEvent.ALT_DOWN_MASK)) != 0 && !(e instanceof KeyEvent && ((KeyEvent)e).getKeyCode() == KeyEvent.VK_ALT)) { try { if (ourStickyAltField == null) { Class<?> aClass = Class.forName("com.sun.java.swing.plaf.windows.WindowsRootPaneUI$AltProcessor"); ourStickyAltField = ReflectionUtil.getDeclaredField(aClass, "menuCanceledOnPress"); } if (ourStickyAltField != null) { ourStickyAltField.set(null, true); } } catch (Exception exception) { LOG.error(exception); } } } else if (SystemInfo.isWindowsXP && e instanceof KeyEvent && ((KeyEvent)e).getKeyCode() == KeyEvent.VK_ALT) { ((KeyEvent)e).consume(); // IDEA-17359 } }
private static void removeAllCovariantMethods(final List<Method> actualMethods, final Method method, final Map<Method, Method> covariantMethods) { if ((method.getModifiers() & Constants.ACC_SYNTHETIC) != 0) { return; } for (Iterator<Method> it = actualMethods.iterator(); it.hasNext();) { Method actualMethod = it.next(); if (actualMethod.equals(method)) { continue; } if (!actualMethod.getName().equals(method.getName()) || !Arrays.equals(actualMethod.getParameterTypes(), method.getParameterTypes())) { continue; } if (ReflectionUtil.isAssignable(actualMethod.getReturnType(), method.getReturnType())) { if ((actualMethod.getModifiers() & Constants.ACC_ABSTRACT) != 0 || (actualMethod.getModifiers() & Constants.ACC_SYNTHETIC) != 0) { covariantMethods.put(actualMethod, method); //generate bridge } else { it.remove(); } } } }
/** * Returns {@code pid} for Windows process * @param process Windows process * @return pid of the {@code process} */ public static int getProcessPid(Process process) { if (process.getClass().getName().equals("java.lang.Win32Process") || process.getClass().getName().equals("java.lang.ProcessImpl")) { try { long handle = ReflectionUtil.getField(process.getClass(), process, long.class, "handle"); Kernel32 kernel = Kernel32.INSTANCE; WinNT.HANDLE winHandle = new WinNT.HANDLE(); winHandle.setPointer(Pointer.createConstant(handle)); return kernel.GetProcessId(winHandle); } catch (Throwable e) { throw new IllegalStateException(e); } } else { throw new IllegalStateException("Unknown Process implementation"); } }
public void testResetField() throws Exception { final Reset reset = new Reset(); ReflectionUtil.resetField(reset, String.class, "STRING"); assertNull(reset.STRING); ReflectionUtil.resetField(reset, boolean.class, "BOOLEAN"); assertFalse(reset.BOOLEAN); ReflectionUtil.resetField(reset, int.class, "INT"); assertEquals(0, reset.INT); ReflectionUtil.resetField(reset, double.class, "DOUBLE"); assertEquals(0d, reset.DOUBLE); ReflectionUtil.resetField(reset, float.class, "FLOAT"); assertEquals(0f, reset.FLOAT); ReflectionUtil.resetField(Reset.class, String.class, "STATIC_STRING"); assertNull(Reset.STATIC_STRING); }
@Override public void filePathsDirty(@Nullable final Collection<FilePath> filesDirty, @Nullable final Collection<FilePath> dirsRecursivelyDirty) { try { final MultiMap<AbstractVcs, FilePath> filesConverted = groupByVcs(filesDirty); final MultiMap<AbstractVcs, FilePath> dirsConverted = groupByVcs(dirsRecursivelyDirty); if (filesConverted.isEmpty() && dirsConverted.isEmpty()) return; if (LOG.isDebugEnabled()) { LOG.debug("paths dirty: " + filesConverted + "; " + dirsConverted + "; " + ReflectionUtil.findCallerClass(3)); } boolean hasSomethingDirty; synchronized (LOCK) { if (!myReady) return; markDirty(myDirtBuilder, filesConverted, false); markDirty(myDirtBuilder, dirsConverted, true); hasSomethingDirty = !myDirtBuilder.isEmpty(); } if (hasSomethingDirty) { myChangeListManager.scheduleUpdate(); } } catch (ProcessCanceledException ignore) { } }
protected static <T extends PsiNamedElement> int getChildIndex(T element, PsiElement parent, String name, Class<T> hisClass) { PsiElement[] children = parent.getChildren(); int index = 0; for (PsiElement child : children) { if (ReflectionUtil.isAssignable(hisClass, child.getClass())) { T namedChild = hisClass.cast(child); final String childName = namedChild.getName(); if (Comparing.equal(name, childName)) { if (namedChild.equals(element)) { return index; } index++; } } } return index; }
@Nullable protected static <T extends PsiNamedElement> T restoreElementInternal(@NotNull PsiElement parent, String name, int index, @NotNull Class<T> hisClass) { PsiElement[] children = parent.getChildren(); for (PsiElement child : children) { if (ReflectionUtil.isAssignable(hisClass, child.getClass())) { T namedChild = hisClass.cast(child); final String childName = namedChild.getName(); if (Comparing.equal(name, childName)) { if (index == 0) { return namedChild; } index--; } } } return null; }
@NotNull @Override public Collection<StructureViewExtension> getAllExtensions(@NotNull Class<? extends PsiElement> type) { Collection<StructureViewExtension> result = myImplExtensions.get(type); if (result == null) { MultiValuesMap<Class<? extends PsiElement>, StructureViewExtension> map = myExtensions.getValue(); for (Class<? extends PsiElement> registeredType : map.keySet()) { if (ReflectionUtil.isAssignable(registeredType, type)) { final Collection<StructureViewExtension> extensions = map.get(registeredType); for (StructureViewExtension extension : extensions) { myImplExtensions.put(type, extension); } } } result = myImplExtensions.get(type); if (result == null) return Collections.emptyList(); } return result; }
private void assertSearchScope(GlobalSearchScope searchScope, String... expectedPaths) { Collection<VirtualFile> roots; if (searchScope instanceof DelegatingGlobalSearchScope) { searchScope = ReflectionUtil.getField(DelegatingGlobalSearchScope.class, searchScope, GlobalSearchScope.class, "myBaseScope"); } if (searchScope instanceof ModuleWithDependenciesScope) { roots = ((ModuleWithDependenciesScope)searchScope).getRoots(); } else { roots = ((LibraryRuntimeClasspathScope)searchScope).getRoots(); } final List<VirtualFile> entries = new ArrayList<VirtualFile>(roots); entries.removeAll(Arrays.asList(ProjectRootManager.getInstance(myProject).orderEntries().sdkOnly().classes().getRoots())); List<String> actualPaths = new ArrayList<String>(); for (VirtualFile each : entries) { actualPaths.add(each.getPresentableUrl()); } assertPaths(expectedPaths, actualPaths); }
@Override public void initComponent() { final AnyBarIcon anyBarIcon = new AnyBarIcon(AppIcon.getInstance()); for (Field field : ReflectionUtil.getClassDeclaredFields(AppIcon.class)) { if (AppIcon.class.isAssignableFrom(field.getType())) { try { field.setAccessible(true); field.set(null, anyBarIcon); } catch (IllegalAccessException e) { Logger.getInstance(AnyBarConnector.class).error(e); } } } }
public FIELD_TYPE getField() { if (myWagonManagerCache == null) { Object value = ReflectionUtil.getField(myHostClass, myHost, null, myFieldName); //noinspection unchecked myWagonManagerCache = (FIELD_TYPE)value; } return myWagonManagerCache; }
protected JFormattedTextField prepareNumberEditor(@NonNls final String fieldName) { final NumberFormat formatter = NumberFormat.getIntegerInstance(); formatter.setParseIntegerOnly(true); final JFormattedTextField valueField = new JFormattedTextField(formatter); Object value = ReflectionUtil.getField(getClass(), this, null, fieldName); valueField.setValue(value); valueField.setColumns(2); // hack to work around text field becoming unusably small sometimes when using GridBagLayout valueField.setMinimumSize(valueField.getPreferredSize()); UIUtil.fixFormattedField(valueField); final Document document = valueField.getDocument(); document.addDocumentListener(new DocumentAdapter() { @Override public void textChanged(DocumentEvent evt) { try { valueField.commitEdit(); final Number number = (Number)valueField.getValue(); ReflectionUtil.setField(BaseInspection.this.getClass(), BaseInspection.this, int.class, fieldName, number.intValue()); } catch (ParseException e) { // No luck this time. Will update the field when correct value is entered. } } }); return valueField; }
@Nullable private static <T> T getRootElement(final PsiFile file, final Class<T> domClass, final Module module) { if (!(file instanceof XmlFile)) return null; final DomManager domManager = DomManager.getDomManager(file.getProject()); final DomFileElement<DomElement> element = domManager.getFileElement((XmlFile)file, DomElement.class); if (element == null) return null; final DomElement root = element.getRootElement(); if (!ReflectionUtil.isAssignable(domClass, root.getClass())) return null; return (T)root; }
private Map<Thread, Thread> getShutdownHooks() { Class clazz; try { clazz = Class.forName("java.lang.ApplicationShutdownHooks"); } catch (ClassNotFoundException e) { // we can ignore this one return Collections.emptyMap(); } return ReflectionUtil.getStaticFieldValue(clazz, Map.class, "hooks"); }
private static boolean isPsiClassType(GenericDomValue element) { final Class genericValueParameter = DomUtil.getGenericValueParameter(element.getDomElementType()); if (genericValueParameter != null && (ReflectionUtil.isAssignable(genericValueParameter, PsiClass.class) || ReflectionUtil.isAssignable(genericValueParameter, PsiType.class))) { return true; } return false; }
@Nullable public static JavaMethod findGetter(Class aClass, String propertyName) { final String capitalized = StringUtil.capitalize(propertyName); Method method = ReflectionUtil.getMethod(aClass, "get" + capitalized); if (method != null) return JavaMethod.getMethod(aClass, method); method = ReflectionUtil.getMethod(aClass, "is" + capitalized); if (method == null) return null; final JavaMethod javaMethod = JavaMethod.getMethod(aClass, method); return canHaveIsPropertyGetterPrefix(javaMethod.getGenericReturnType()) ? javaMethod : null; }
static Object instantiateTool(@NotNull Class<?> toolClass) { try { return ReflectionUtil.newInstance(toolClass); } catch (RuntimeException e) { LOG.error(e.getCause()); } return null; }
@Override public boolean canNavigate(DomElement element) { final Class<DomElement> aClass = (Class<DomElement>)ReflectionUtil.getRawType(myChildDescription.getType()); final DomElement domElement = element.getParentOfType(aClass, false); return domElement != null && myCollectionElements.contains(domElement); }
@Nullable public static Type extractCollectionElementType(Type returnType) { if (returnType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)returnType; final Type rawType = parameterizedType.getRawType(); if (rawType instanceof Class) { final Class<?> rawClass = (Class<?>)rawType; if (List.class.equals(rawClass) || Collection.class.equals(rawClass)) { final Type[] arguments = ReflectionUtil.getActualTypeArguments(parameterizedType); if (arguments.length == 1) { final Type argument = arguments[0]; if (argument instanceof WildcardType) { final Type[] upperBounds = ((WildcardType)argument).getUpperBounds(); if (upperBounds.length == 1) { return upperBounds[0]; } } else if (argument instanceof ParameterizedType) { if (DomUtil.getGenericValueParameter(argument) != null) { return argument; } } else if (argument instanceof Class) { return argument; } } } } } return null; }
private boolean shouldBeIgnored(Object object) { if (object instanceof CellRendererPane) return true; if (object == null) { return true; } for (Class aClass : myControlsToIgnore) { if (ReflectionUtil.isAssignable(aClass, object.getClass())) { return true; } } return false; }
private boolean isAddMethod(JavaMethod method) { final XmlName tagName = extractTagName(method, "add"); if (tagName == null) return false; final Type type = myCollectionChildrenTypes.get(tagName); if (type == null || !ReflectionUtil.getRawType(type).isAssignableFrom(method.getReturnType())) return false; return ADDER_PARAMETER_TYPES.containsAll(Arrays.asList(method.getParameterTypes())); }
@Override public void navigate(DomElement element) { final Class<DomElement> aClass = (Class<DomElement>)ReflectionUtil.getRawType(myChildDescription.getType()); final DomElement domElement = element.getParentOfType(aClass, false); int index = myCollectionElements.indexOf(domElement); if (index < 0) index = 0; myCollectionPanel.getTable().setRowSelectionInterval(index, index); }
private static Object info(Runnable r) { if (!(r instanceof FutureTask)) return r; Object sync = ReflectionUtil.getField(FutureTask.class, r, null, "sync"); // FutureTask.sync in <=JDK7 Object o = sync == null ? r : sync; Object callable = ReflectionUtil.getField(o.getClass(), o, Callable.class, "callable"); // FutureTask.callable or Sync.callable if (callable == null) return null; Object task = ReflectionUtil.getField(callable.getClass(), callable, null, "task"); // java.util.concurrent.Executors.RunnableAdapter.task return task == null ? callable : task; }
private static void enableRemoveOnCancelPolicy(ScheduledThreadPoolExecutor executor) { if (Patches.USE_REFLECTION_TO_ACCESS_JDK7) { try { Method setRemoveOnCancelPolicy = ReflectionUtil.getDeclaredMethod(ScheduledThreadPoolExecutor.class, "setRemoveOnCancelPolicy", boolean.class); setRemoveOnCancelPolicy.invoke(executor, true); } catch (Exception ignored) { } } }
@Nullable @Override protected Boolean create(LanguageFileType fileType) { Class<?> ftClass = fileType.getClass(); String methodName = "extractCharsetFromFileContent"; Class declaring1 = ReflectionUtil.getMethodDeclaringClass(ftClass, methodName, Project.class, VirtualFile.class, String.class); Class declaring2 = ReflectionUtil.getMethodDeclaringClass(ftClass, methodName, Project.class, VirtualFile.class, CharSequence.class); return !LanguageFileType.class.equals(declaring1) || !LanguageFileType.class.equals(declaring2); }
@TestOnly public static void checkProjectLeak() throws Exception { Processor<Project> isReallyLeak = new Processor<Project>() { @Override public boolean process(Project project) { return !project.isDefault() && !((ProjectImpl)project).isLight(); } }; Collection<Object> roots = new ArrayList<Object>(Arrays.asList(ApplicationManager.getApplication(), Extensions.getRootArea())); ClassLoader classLoader = LeakHunter.class.getClassLoader(); Vector<Class> allLoadedClasses = ReflectionUtil.getField(classLoader.getClass(), classLoader, Vector.class, "classes"); roots.addAll(allLoadedClasses); // inspect static fields of all loaded classes checkLeak(roots, ProjectImpl.class, isReallyLeak); }
private static void captureMemorySnapshot() { try { Method snapshot = ReflectionUtil.getMethod(Class.forName("com.intellij.util.ProfilingUtil"), "forceCaptureMemorySnapshot"); if (snapshot != null) { snapshot.invoke(null); } } catch (Exception ignored) { } }
public AwtPopupWrapper(Popup popup, JBPopup jbPopup) { myPopup = popup; myJBPopup = jbPopup; if (SystemInfo.isMac && UIUtil.isUnderAquaLookAndFeel()) { final Component c = ReflectionUtil.getField(Popup.class, myPopup, Component.class, "component"); c.setBackground(UIUtil.getPanelBackground()); } }
public void hide(boolean dispose) { myPopup.hide(); Window wnd = getWindow(); if (wnd instanceof JWindow) { JRootPane rootPane = ((JWindow)wnd).getRootPane(); if (rootPane != null) { ReflectionUtil.resetField(rootPane, "clientProperties"); final Container cp = rootPane.getContentPane(); if (cp != null) { cp.removeAll(); } } } }
public static void updateFrameClass() { try { final Toolkit toolkit = Toolkit.getDefaultToolkit(); final Class<? extends Toolkit> aClass = toolkit.getClass(); if ("sun.awt.X11.XToolkit".equals(aClass.getName())) { ReflectionUtil.setField(aClass, toolkit, null, "awtAppClassName", getFrameClass()); } } catch (Exception ignore) { } }