blob: d7604fa61b70b02e3011a94cecd96e8aefb07552 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
/*
* Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Eike Stepper - initial API and implementation
*/
package org.eclipse.net4j.util;
/**
* Provides a single static {@link #adapt(Object, Class) adapt()} method that conveniently and safely wraps the
* Platform's adaptation framework.
*
* @author Eike Stepper
*/
public final class AdapterUtil
{
private AdapterUtil()
{
}
public static <TYPE> TYPE adapt(Object object, Class<TYPE> type)
{
if (object == null)
{
return null;
}
Object adapter = null;
if (type.isInstance(object))
{
adapter = object;
}
else
{
try
{
adapter = AdaptableHelper.adapt(object, type);
if (adapter == null)
{
adapter = AdapterManagerHelper.adapt(object, type);
}
}
catch (Throwable ignore)
{
}
}
@SuppressWarnings("unchecked")
TYPE result = (TYPE)adapter;
return result;
}
/**
* Nested class to factor out dependencies on org.eclipse.core.runtime
*
* @author Eike Stepper
*/
private static final class AdaptableHelper
{
public static Object adapt(Object object, Class<?> type)
{
if (object instanceof org.eclipse.core.runtime.IAdaptable)
{
return ((org.eclipse.core.runtime.IAdaptable)object).getAdapter(type);
}
return null;
}
}
/**
* Nested class to factor out dependencies on org.eclipse.core.runtime
*
* @author Eike Stepper
*/
private static final class AdapterManagerHelper
{
private static org.eclipse.core.runtime.IAdapterManager adapterManager = org.eclipse.core.runtime.Platform
.getAdapterManager();
public static Object adapt(Object object, Class<?> type)
{
if (adapterManager != null)
{
return adapterManager.getAdapter(object, type);
}
return null;
}
}
}
|