有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java何时使用IAdaptable?

给定一个类型为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) {
        // ...
    }
    

共 (1) 个答案

  1. # 1 楼答案

    这很难给出一般规则

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

    从用户界面对象到基础对象的转换通常使用IAdapterFactory来完成,该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方法