给定一个 A 类型的对象,并且希望在可能的情况下将其转换为 B 类型,什么时候适合使用以下各项?
直接转换和/或
instanceof
检查if(a instanceof B) { B b = (B)a; // ... }
通过
IAdaptable.getAdapter
进行转换// assuming A implements/extends IAdaptable B b = (B)a.getAdapter(B.class); if(b != null) { // ... }
当
时,通过A
无法隐式转换为`IAdaptableIAdaptable
进行转换B b = (a instanceof IAdaptable ? (B)((IAdaptable)a).getAdapter(B.class) : a instanceof B ? (B)a : null); if(b != null) { // ... }
通过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/