com.intellij.util.ReflectionUtil Java Examples

The following examples show how to use com.intellij.util.ReflectionUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CloneUtils.java    From EasyCode with MIT License 6 votes vote down vote up
/**
 * 复制属性
 *
 * @param oldEntity 就实体
 * @param newEntity 新实例
 */
private static void copyIgnoreProp(Object oldEntity, Object newEntity) {
    // 类型不一样直接返回
    if (!Objects.equals(oldEntity.getClass(), newEntity.getClass())) {
        return;
    }
    // 获取所有字段
    List<Field> fieldList = ReflectionUtil.collectFields(oldEntity.getClass());
    if (CollectionUtil.isEmpty(fieldList)) {
        return;
    }
    fieldList.forEach(field -> {
        if (field.getAnnotation(JsonIgnore.class) != null) {
            // 设置允许访问
            field.setAccessible(true);
            // 复制字段
            try {
                field.set(newEntity, field.get(oldEntity));
            } catch (IllegalAccessException e) {
                ExceptionUtil.rethrow(e);
            }
        }
    });
}
 
Example #2
Source File: DialogWrapper.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static void cleanupRootPane(@Nullable JRootPane rootPane) {
  if (rootPane == null) return;
  // Must be preserved:
  //   Component#appContext, Component#appContext, Container#component
  //   JRootPane#contentPane due to popup recycling & our border styling
  // Must be cleared:
  //   JComponent#clientProperties, contentPane children
  RepaintManager.currentManager(rootPane).removeInvalidComponent(rootPane);
  unregisterKeyboardActions(rootPane);
  Container contentPane = rootPane.getContentPane();
  if (contentPane != null) contentPane.removeAll();
  if (rootPane.getGlassPane() instanceof IdeGlassPane && rootPane.getClass() == JRootPane.class) {
    rootPane.setGlassPane(new JPanel()); // resizeable AbstractPopup but not DialogWrapperPeer
  }
  ReflectionUtil.clearOwnFields(rootPane, field -> {
    String clazz = field.getDeclaringClass().getName();
    // keep AWT and Swing fields intact, except some
    if (!clazz.startsWith("java.") && !clazz.startsWith("javax.")) return true;
    String name = field.getName();
    return "clientProperties".equals(name);
  });
}
 
Example #3
Source File: MultiplePsiFilesPerDocumentFileViewProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
@Nullable
public PsiElement findElementAt(int offset, @Nonnull Class<? extends Language> lang) {
  final PsiFile mainRoot = getPsi(getBaseLanguage());
  PsiElement ret = null;
  for (final Language language : getLanguages()) {
    if (!ReflectionUtil.isAssignable(lang, language.getClass())) continue;
    if (lang.equals(Language.class) && !getLanguages().contains(language)) continue;

    final PsiFile psiRoot = getPsi(language);
    final PsiElement psiElement = findElementAt(psiRoot, offset);
    if (psiElement == null || psiElement instanceof OuterLanguageElement) continue;
    if (ret == null || psiRoot != mainRoot) {
      ret = psiElement;
    }
  }
  return ret;
}
 
Example #4
Source File: FileModifier.java    From consulo with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the equivalent file modifier that could be applied to the
 * non-physical copy of the file used to preview the modification.
 * May return itself if the action doesn't depend on the file.
 *
 * @param target target non-physical file
 * @return the action that could be applied to the non-physical copy of the file.
 * Returns null if operation is not supported.
 */
@Nullable
default FileModifier getFileModifierForPreview(@Nonnull PsiFile target) {
  if (!startInWriteAction()) return null;
  for (Field field : ReflectionUtil.collectFields(((Object)this).getClass())) {
    if (Modifier.isStatic(field.getModifiers())) continue;
    Class<?> type = field.getType();
    if (field.getAnnotation(SafeFieldForPreview.class) != null) continue;
    while (type.isArray()) type = type.getComponentType();
    if (type.isPrimitive() || type.isEnum() || type.equals(String.class) || type.equals(Class.class) || type.equals(Integer.class) || type.equals(Boolean.class) ||
        // Back-link to the parent inspection looks safe, as inspection should not depend on the file
        (field.isSynthetic() && field.getName().equals("this$0") && LocalInspectionTool.class.isAssignableFrom(type))) {
      continue;
    }
    return null;
  }
  // No PSI-specific state: it's safe to apply this action to a file copy
  return this;
}
 
Example #5
Source File: ReflectionUtilTest.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #6
Source File: JBScrollPane.java    From consulo with Apache License 2.0 6 votes vote down vote up
public static boolean canBePreprocessed(MouseEvent e, JScrollBar bar) {
  if (e.getID() == MouseEvent.MOUSE_MOVED || e.getID() == MouseEvent.MOUSE_PRESSED) {
    ScrollBarUI ui = bar.getUI();
    if (ui instanceof BasicScrollBarUI) {
      BasicScrollBarUI bui = (BasicScrollBarUI)ui;
      try {
        Rectangle rect = (Rectangle)ReflectionUtil.getDeclaredMethod(BasicScrollBarUI.class, "getThumbBounds", ArrayUtil.EMPTY_CLASS_ARRAY).invoke(bui);
        Point point = SwingUtilities.convertPoint(e.getComponent(), e.getX(), e.getY(), bar);
        return !rect.contains(point);
      }
      catch (Exception e1) {
        return true;
      }
    }
  }
  return true;
}
 
Example #7
Source File: AbstractElementSignatureProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: ActionGroup.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #9
Source File: DefaultStateSerializer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
@Nullable
public static <T> T deserializeState(@Nullable Element stateElement, Class <T> stateClass) throws StateStorageException {
  if (stateElement == null) return null;

  if (stateClass.equals(Element.class)) {
    //assert mergeInto == null;
    return (T)stateElement;
  }
  else if (JDOMExternalizable.class.isAssignableFrom(stateClass)) {
    final T t = ReflectionUtil.newInstance(stateClass);
    try {
      ((JDOMExternalizable)t).readExternal(stateElement);
      return t;
    }
    catch (InvalidDataException e) {
      throw new StateStorageException(e);
    }
  }
  else {
    return XmlSerializer.deserialize(stateElement, stateClass);
  }
}
 
Example #10
Source File: SystemShortcuts.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static
@Nonnull
String getDescription(@Nonnull AWTKeyStroke systemHotkey) {
  if (ourShkClass == null) ourShkClass = ReflectionUtil.forName("java.awt.desktop.SystemHotkey");
  if (ourShkClass == null) return ourUnknownSysAction;

  if (ourMethodGetDescription == null) ourMethodGetDescription = ReflectionUtil.getMethod(ourShkClass, "getDescription");
  String result = null;
  try {
    result = (String)ourMethodGetDescription.invoke(systemHotkey);
  }
  catch (Throwable e) {
    Logger.getInstance(SystemShortcuts.class).error(e);
  }
  return result == null ? ourUnknownSysAction : result;
}
 
Example #11
Source File: AndroidUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private static GradleSettingsFile parseSettings(Project project) {
  // Get the PSI for settings.gradle. In IntelliJ it is just this, but Android Studio uses a VirtualFile.
  //GradleSettingsFile parsedSettings =
  //  BuildModelContext.create(project).getOrCreateSettingsFile(project);
  // We need to use reflection to create the expression so this code can be compiled (and run) in all the
  // code bases that are currently supported.
  boolean isAndroidStudio = FlutterUtils.isAndroidStudio();
  VirtualFile projectDir = requireNonNull(FlutterUtils.getProjectRoot(project));
  Object param = isAndroidStudio ? projectDir.findChild(SdkConstants.FN_SETTINGS_GRADLE) : project;
  if (param == null) {
    return null;
  }
  Method method =
    ReflectionUtil.getMethod(BuildModelContext.class, "getOrCreateSettingsFile", isAndroidStudio ? VirtualFile.class : Project.class);
  if (method == null) {
    return null;
  }
  try {
    return (GradleSettingsFile)method.invoke(makeBuildModelContext(project), param);
  }
  catch (InvocationTargetException | IllegalAccessException e) {
    return null;
  }
}
 
Example #12
Source File: AndroidUtils.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Nullable
private static GradleSettingsFile parseSettings(Project project) {
  // Get the PSI for settings.gradle. In IntelliJ it is just this, but Android Studio uses a VirtualFile.
  //GradleSettingsFile parsedSettings =
  //  BuildModelContext.create(project).getOrCreateSettingsFile(project);
  // We need to use reflection to create the expression so this code can be compiled (and run) in all the
  // code bases that are currently supported.
  boolean isAndroidStudio = FlutterUtils.isAndroidStudio();
  VirtualFile projectDir = requireNonNull(FlutterUtils.getProjectRoot(project));
  Object param = isAndroidStudio ? projectDir.findChild(SdkConstants.FN_SETTINGS_GRADLE) : project;
  if (param == null) {
    return null;
  }
  Method method =
    ReflectionUtil.getMethod(BuildModelContext.class, "getOrCreateSettingsFile", isAndroidStudio ? VirtualFile.class : Project.class);
  if (method == null) {
    return null;
  }
  try {
    return (GradleSettingsFile)method.invoke(makeBuildModelContext(project), param);
  }
  catch (InvocationTargetException | IllegalAccessException e) {
    return null;
  }
}
 
Example #13
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void initPre41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //registerComponents();
    Method method = ReflectionUtil.getDeclaredMethod(ProjectImpl.class, "registerComponents");
    assert (method != null);
    try {
      method.invoke(this);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    getStateStore().setPath(path, true, null);
    super.init(indicator);
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #14
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void init41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //ProjectManagerImpl.initProject(path, this, true, null, null);
    Method method = ReflectionUtil
      .getDeclaredMethod(ProjectManagerImpl.class, "initProject", Path.class, ProjectImpl.class, boolean.class, Project.class,
                         ProgressIndicator.class);
    assert (method != null);
    try {
      method.invoke(null, path, this, true, null, null);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #15
Source File: FlutterProjectSystem.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("override")
@NotNull
public Collection<PsiElementFinder> getPsiElementFinders() {
  Method finders = ReflectionUtil.getMethod(gradleProjectSystem.getClass(), "getPsiElementFinders");
  if (finders == null) {
    FlutterUtils.warn(LOG, "No method found: GradleProjectSystem.getPsiElementFinders()");
    return Collections.emptyList();
  }
  try {
    //noinspection unchecked
    return (Collection<PsiElementFinder>)finders.invoke(gradleProjectSystem);
  }
  catch (IllegalAccessException | InvocationTargetException e) {
    LOG.error(e);
    throw new IllegalArgumentException(e);
  }
}
 
Example #16
Source File: FlutterProjectSystem.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public String mergeBuildFiles(@NotNull String dependencies,
                              @NotNull String destinationContents,
                              @Nullable String supportLibVersionFilter) {
  Method finders = ReflectionUtil.getMethod(gradleProjectSystem.getClass(), "mergeBuildFiles");
  if (finders == null) {
    FlutterUtils.warn(LOG, "No method found: GradleProjectSystem.getPsiElementFinders()");
    return null;
  }
  try {
    //noinspection unchecked
    return (String)finders.invoke(gradleProjectSystem, dependencies, destinationContents, supportLibVersionFilter);
  }
  catch (IllegalAccessException | InvocationTargetException e) {
    LOG.error(e);
    throw new IllegalArgumentException(e);
  }
}
 
Example #17
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void initPre41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //registerComponents();
    Method method = ReflectionUtil.getDeclaredMethod(ProjectImpl.class, "registerComponents");
    assert (method != null);
    try {
      method.invoke(this);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    getStateStore().setPath(path, true, null);
    super.init(indicator);
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #18
Source File: AndroidModuleLibraryManager.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void init41(@Nullable ProgressIndicator indicator) {
  boolean finished = false;
  try {
    //ProjectManagerImpl.initProject(path, this, true, null, null);
    Method method = ReflectionUtil
      .getDeclaredMethod(ProjectManagerImpl.class, "initProject", Path.class, ProjectImpl.class, boolean.class, Project.class,
                         ProgressIndicator.class);
    assert (method != null);
    try {
      method.invoke(null, path, this, true, null, null);
    }
    catch (IllegalAccessException | InvocationTargetException e) {
      throw new RuntimeException(e);
    }
    finished = true;
  }
  finally {
    if (!finished) {
      TransactionGuard.submitTransaction(this, () -> WriteAction.run(() -> Disposer.dispose(this)));
    }
  }
}
 
Example #19
Source File: FlutterProjectSystem.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@SuppressWarnings("override")
@NotNull
public Collection<PsiElementFinder> getPsiElementFinders() {
  Method finders = ReflectionUtil.getMethod(gradleProjectSystem.getClass(), "getPsiElementFinders");
  if (finders == null) {
    FlutterUtils.warn(LOG, "No method found: GradleProjectSystem.getPsiElementFinders()");
    return Collections.emptyList();
  }
  try {
    //noinspection unchecked
    return (Collection<PsiElementFinder>)finders.invoke(gradleProjectSystem);
  }
  catch (IllegalAccessException | InvocationTargetException e) {
    LOG.error(e);
    throw new IllegalArgumentException(e);
  }
}
 
Example #20
Source File: FlutterProjectSystem.java    From flutter-intellij with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public String mergeBuildFiles(@NotNull String dependencies,
                              @NotNull String destinationContents,
                              @Nullable String supportLibVersionFilter) {
  Method finders = ReflectionUtil.getMethod(gradleProjectSystem.getClass(), "mergeBuildFiles");
  if (finders == null) {
    FlutterUtils.warn(LOG, "No method found: GradleProjectSystem.getPsiElementFinders()");
    return null;
  }
  try {
    //noinspection unchecked
    return (String)finders.invoke(gradleProjectSystem, dependencies, destinationContents, supportLibVersionFilter);
  }
  catch (IllegalAccessException | InvocationTargetException e) {
    LOG.error(e);
    throw new IllegalArgumentException(e);
  }
}
 
Example #21
Source File: CodeGenerateServiceImpl.java    From EasyCode with MIT License 6 votes vote down vote up
/**
 * 获取默认参数
 *
 * @return 参数
 */
private Map<String, Object> getDefaultParam() {
    // 系统设置
    Settings settings = Settings.getInstance();
    Map<String, Object> param = new HashMap<>(20);
    // 作者
    param.put("author", settings.getAuthor());
    //工具类
    param.put("tool", GlobalTool.getInstance());
    param.put("time", TimeUtils.getInstance());
    // 项目路径
    param.put("projectPath", project.getBasePath());
    // Database数据库工具
    param.put("dbUtil", ReflectionUtil.newInstance(DbUtil.class));
    param.put("dasUtil", ReflectionUtil.newInstance(DasUtil.class));
    return param;
}
 
Example #22
Source File: IdeMouseEventDispatcher.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * This method patches event if it concerns side buttons like 4 (Backward) or 5 (Forward)
 * AND it's not single-click event. We won't support double-click for side buttons.
 * Also some JDK bugs produce zero-click events for side buttons.
 *
 * @return true if event was patched
 */
public static boolean patchClickCount(final MouseEvent e) {
  if (e.getClickCount() != 1 && e.getButton() > 3) {
    ReflectionUtil.setField(MouseEvent.class, e, int.class, "clickCount", 1);
    return true;
  }
  return false;
}
 
Example #23
Source File: SkipDefaultValuesSerializationFilters.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
Object getDefaultBean(@Nonnull Object bean) {
  Class<?> c = bean.getClass();
  Object o = myDefaultBeans.get(c);
  if (o == null) {
    o = ReflectionUtil.newInstance(c);
    configure(o);

    myDefaultBeans.put(c, o);
  }
  return o;
}
 
Example #24
Source File: CommonCodeStyleSettings.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(Object obj) {
  if (obj instanceof CommonCodeStyleSettings) {
    if (ReflectionUtil.comparePublicNonFinalFields(this, obj) &&
        mySoftMargins.equals(((CommonCodeStyleSettings)obj).mySoftMargins) &&
        Comparing.equal(myIndentOptions, ((CommonCodeStyleSettings)obj).getIndentOptions()) &&
        arrangementSettingsEqual((CommonCodeStyleSettings)obj)) {
      return true;
    }
  }
  return false;
}
 
Example #25
Source File: PopupComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
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();
      }
    }
  }
}
 
Example #26
Source File: PopupComponent.java    From consulo with Apache License 2.0 5 votes vote down vote up
public AwtPopupWrapper(Popup popup, JBPopup jbPopup) {
  myPopup = popup;
  myJBPopup = jbPopup;

  if (SystemInfo.isMac && UIUtil.isUnderAquaLookAndFeel()) {
    final Component c = (Component)ReflectionUtil.getField(Popup.class, myPopup, Component.class, "component");
    c.setBackground(UIUtil.getPanelBackground());
  }
}
 
Example #27
Source File: UiInspectorAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static Color getBorderColor(@Nonnull Border value) {
  if (value instanceof LineBorder) {
    return ((LineBorder)value).getLineColor();
  }
  else if (value instanceof CustomLineBorder) {
    try {
      return (Color)ReflectionUtil.findField(CustomLineBorder.class, Color.class, "myColor").get(value);
    }
    catch (Exception ignore) {
    }
  }

  return null;
}
 
Example #28
Source File: FontLayoutService.java    From consulo with Apache License 2.0 5 votes vote down vote up
private DefaultFontLayoutService() {
  myHandleCharWidthMethod = ReflectionUtil.getDeclaredMethod(FontDesignMetrics.class, "handleCharWidth", int.class);
  if (myHandleCharWidthMethod == null) {
    LOG.warn("Couldn't access FontDesignMetrics.handleCharWidth method");
  }
  myGetLatinCharWidthMethod = ReflectionUtil.getDeclaredMethod(FontDesignMetrics.class, "getLatinCharWidth", char.class);
  if (myGetLatinCharWidthMethod == null) {
    LOG.warn("Couldn't access FontDesignMetrics.getLatinCharWidth method");
  }
}
 
Example #29
Source File: VcsDirtyScopeManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
@javax.annotation.Nullable
private static Class findFirstInterestingCallerClass() {
  for (int i = 1; i <= 5; i++) {
    Class clazz = ReflectionUtil.findCallerClass(i);
    if (clazz == null || !clazz.getName().contains(VcsDirtyScopeManagerImpl.class.getName())) return clazz;
  }
  return null;
}
 
Example #30
Source File: XmlSerializerUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static <T> T createCopy(@Nonnull T from) {
  try {
    @SuppressWarnings("unchecked")
    T to = (T)ReflectionUtil.newInstance(from.getClass());
    copyBean(from, to);
    return to;
  }
  catch (Exception ignored) {
    return null;
  }
}