java - 何时使用 IAdaptable?

标签 java eclipse eclipse-plugin

给定一个 A 类型的对象,并且希望在可能的情况下将其转换为 B 类型,什么时候适合使用以下各项?

  1. 直接转换和/或instanceof检查

    if(a instanceof B) {
        B b = (B)a;
        // ...
    }
    
  2. 通过IAdaptable.getAdapter进行转换

    // assuming A implements/extends IAdaptable
    B b = (B)a.getAdapter(B.class);
    if(b != null) {
        // ...
    }
    
  3. A无法隐式转换为`IAdaptable

    时,通过IAdaptable进行转换

    B b = (a instanceof IAdaptable ? (B)((IAdaptable)a).getAdapter(B.class) : a instanceof B ? (B)a : null);
    if(b != null) {
        // ...
    }
    
  4. 通过IAdapterManager进行转换

    B b = (B)Platform.getAdapterManager().getAdapter(a, B.class);
    if(b != null) {
        // ...
    }
    

最佳答案

这很难给出一般规则。

当您从 Eclipse 项目 View 中获得类似当前选择的内容时,该对象是用户界面而不是底层对象(例如项目或文件)。 instanceof 将不起作用。

从用户界面对象到底层对象的转换通常是使用 IAdapterFactory 完成的,它指定一个单独的工厂类来执行转换。在这种情况下,您必须使用 Platform.getAdapterManager().getAdapter

当一个对象实现IAdaptable时,您必须查看文档或源代码以了解它也支持哪些类。

我认为情况 3 不会发生。

我经常使用这个代码来处理大多数事情:

public final class AdapterUtil
{
  /**
   * Get adapter for an object.
   * This version checks first if the object is already the correct type.
   * Next it checks the object is adaptable (not done by the Platform adapter manager).
   * Finally the Platform adapter manager is called.
   *
   * @param adaptableObject Object to examine
   * @param adapterType Adapter type class
   * @return The adapted object or <code>null</code>
   */
  public static <AdapterType> AdapterType adapt(Object adaptableObject, Class<AdapterType> adapterType)
  {  
    // Is the object the desired type?

    if (adapterType.isInstance(adaptableObject))
      return adapterType.cast(adaptableObject);

    // Does object adapt to the type?

    if (adaptableObject instanceof IAdaptable)
     {
       AdapterType result = adapterType.cast(((IAdaptable)adaptableObject).getAdapter(adapterType));
       if (result != null)
         return result;
     }

    // Try the platform adapter manager

    return adapterType.cast(Platform.getAdapterManager().getAdapter(adaptableObject, adapterType));
  }
}

注意:较新版本的 Eclipse 有一个 org.eclipse.core.runtime.Adapters 类,它具有类似的 adapt 方法。

关于java - 何时使用 IAdaptable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25032250/

相关文章:

java - 与 Sonar 插件关联...组 ID 为空

java - 这是如何编写此 <class name> <object name > = new constructor name 的正确方法?

java - Bigquery : how to access another project in Bigquery JAVA API?

java - 如何修复 '<>' 运算符不允许用于源级别 1.7

java - 使用 Eclipse 项目中的 JDK

eclipse - 找不到处理 swagger-codegen-maven-plugin 的市场条目

java - 插入/使用 CompletionProposal 的 eclipse 插件扩展点

java - 正确设置 Maven 3

java - 通过声明的返回类型进行 Spring AOP 切入点

android - 即使没有错误,Eclipse 也不会生成 R.java