Java Code Examples for com.intellij.util.ReflectionUtil

The following examples show how to use com.intellij.util.ReflectionUtil. These examples are extracted from open source projects. 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 Project: EasyCode   Source File: CloneUtils.java    License: 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 Project: EasyCode   Source File: CodeGenerateServiceImpl.java    License: 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 3
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 4
@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 5
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 6
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 7
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 8
@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 9
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 10
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 11
@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
@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 Project: consulo   Source File: FileModifier.java    License: 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 14
Source Project: consulo   Source File: DialogWrapper.java    License: 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 15
Source Project: consulo   Source File: JBScrollPane.java    License: 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 16
Source Project: consulo   Source File: ReflectionUtilTest.java    License: 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 17
Source Project: consulo   Source File: ActionGroup.java    License: 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 18
Source Project: consulo   Source File: DefaultStateSerializer.java    License: 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 19
Source Project: consulo   Source File: SystemShortcuts.java    License: 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 20
@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 21
Source Project: consulo   Source File: AbstractElementSignatureProvider.java    License: 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 22
Source Project: EasyCode   Source File: GlobalTool.java    License: MIT License 5 votes vote down vote up
/**
 * 获取字段,私有属性一样强制访问
 *
 * @param obj       对象
 * @param fieldName 字段名
 * @return 字段值
 */
public Object getField(Object obj, String fieldName) {
    if (obj == null) {
        return null;
    }
    Class<?> cls = obj.getClass();
    return ReflectionUtil.getField(cls, obj, Object.class, fieldName);
}
 
Example 23
private static String getUrl(Object tag) {
  if (tag instanceof BrowserHyperlinkInfo) {
    final Field field = ReflectionUtil.getDeclaredField(tag.getClass(), "myUrl");
    if (field != null) {
      try {
        return (String)field.get(tag);
      }
      catch (Throwable ignored) {
      }
    }
  }
  return null;
}
 
Example 24
private static String getUrl(Object tag) {
  if (tag instanceof BrowserHyperlinkInfo) {
    final Field field = ReflectionUtil.getDeclaredField(tag.getClass(), "myUrl");
    if (field != null) {
      try {
        return (String)field.get(tag);
      }
      catch (Throwable ignored) {
      }
    }
  }
  return null;
}
 
Example 25
Source Project: intellij   Source File: IntellijTestSetupRule.java    License: Apache License 2.0 5 votes vote down vote up
private static void cleanupSwingDataStructures() throws Exception {
  Object manager =
      ReflectionUtil.getDeclaredMethod(
              Class.forName("javax.swing.KeyboardManager"), "getCurrentManager")
          .invoke(null);
  Map<?, ?> componentKeyStrokeMap =
      ReflectionUtil.getField(
          manager.getClass(), manager, Hashtable.class, "componentKeyStrokeMap");
  componentKeyStrokeMap.clear();
  Map<?, ?> containerMap =
      ReflectionUtil.getField(manager.getClass(), manager, Hashtable.class, "containerMap");
  containerMap.clear();
}
 
Example 26
@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;
}
 
Example 27
Source Project: consulo   Source File: ModuleExtensionProviderEP.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public ModuleExtension<?> createImmutable(@Nonnull ModuleRootLayer modifiableRootModel) {
  try {
    Pair<Class<ModuleExtension>, Constructor<ModuleExtension>> value = myImmutableValue.getValue();
    if (value != null) {
      return ReflectionUtil.createInstance(value.getSecond(), key, modifiableRootModel);
    }
  }
  catch (Error e) {
    ModuleExtensionProviderEP.LOGGER.error("Problem with module extension: " + key, e);
  }
  return null;
}
 
Example 28
Source Project: consulo   Source File: ModuleExtensionProviderEP.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public MutableModuleExtension<?> createMutable(@Nonnull ModuleRootLayer modifiableRootModel) {
  try {
    Pair<Class<MutableModuleExtension>, Constructor<MutableModuleExtension>> value = myMutableValue.getValue();
    if (value != null) {
      return ReflectionUtil.createInstance(value.getSecond(), key, modifiableRootModel);
    }
  }
  catch (Error e) {
    ModuleExtensionProviderEP.LOGGER.error("Problem with module extension: " + key, e);
  }
  return null;
}
 
Example 29
Source Project: consulo   Source File: UsageViewImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void clearRendererCache() {
  ApplicationManager.getApplication().assertIsDispatchThread();
  if (myExpandingCollapsing) return; // to avoid quadratic row enumeration
  // clear renderer cache of node preferred size
  TreeUI ui = myTree.getUI();
  if (ui instanceof BasicTreeUI) {
    AbstractLayoutCache treeState = ReflectionUtil.getField(BasicTreeUI.class, ui, AbstractLayoutCache.class, "treeState");
    Rectangle visibleRect = myTree.getVisibleRect();
    int rowForLocation = myTree.getClosestRowForLocation(0, visibleRect.y);
    int visibleRowCount = getVisibleRowCount();
    List<Node> toUpdate = new ArrayList<>();
    for (int i = rowForLocation + visibleRowCount + 1; i >= rowForLocation; i--) {
      final TreePath eachPath = myTree.getPathForRow(i);
      if (eachPath == null) continue;

      treeState.invalidatePathBounds(eachPath);
      Object node = eachPath.getLastPathComponent();
      if (node instanceof UsageNode) {
        toUpdate.add((Node)node);
      }
    }
    queueUpdateBulk(toUpdate, () -> {
      if (!isDisposed()) {
        myTree.repaint(visibleRect);
      }
    });
  }
  else {
    myTree.setCellRenderer(myUsageViewTreeCellRenderer);
  }
}
 
Example 30
Source Project: consulo   Source File: UnixProcessManager.java    License: Apache License 2.0 5 votes vote down vote up
public static int getProcessId(@Nonnull Process process) {
  try {
    if (SystemInfo.IS_AT_LEAST_JAVA9 && "java.lang.ProcessImpl".equals(process.getClass().getName())) {
      //noinspection JavaReflectionMemberAccess
      return ((Long)Process.class.getMethod("pid").invoke(process)).intValue();
    }

    return assertNotNull(ReflectionUtil.getField(process.getClass(), process, int.class, "pid"));
  }
  catch (Throwable t) {
    throw new IllegalStateException("Failed to get PID from instance of " + process.getClass() + ", OS: " + SystemInfo.OS_NAME, t);
  }
}