1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
package org.apache.commons.classscan.util; |
15 | |
|
16 | |
import java.lang.reflect.Array; |
17 | |
import java.util.Arrays; |
18 | |
import java.util.Collection; |
19 | |
import java.util.Comparator; |
20 | |
|
21 | |
import org.apache.commons.classscan.HasName; |
22 | |
import org.apache.commons.classscan.spi.model.HasResolve; |
23 | |
|
24 | |
public class NameSet<V extends HasName & HasResolve> extends ResolveSet<V> { |
25 | |
|
26 | 0 | private final static Comparator<HasName> REVERSE_COMPARE = new Comparator<HasName>() { |
27 | |
@Override |
28 | |
public int compare(HasName l, HasName r) { |
29 | 0 | String left = l.getName(); |
30 | 0 | String right = r.getName(); |
31 | |
|
32 | |
|
33 | 0 | int diff = left.length() - right.length(); |
34 | 0 | if (diff != 0) { |
35 | 0 | return diff; |
36 | |
} |
37 | |
|
38 | 0 | for (int i = left.length(); --i > 0;) { |
39 | 0 | int d = left.charAt(i) - right.charAt(i); |
40 | 0 | if (d != 0) { |
41 | 0 | return d; |
42 | |
} |
43 | 0 | } |
44 | 0 | return 0; |
45 | |
} |
46 | |
}; |
47 | |
|
48 | |
public NameSet(V[] values) { |
49 | 0 | super(values); |
50 | 0 | if(values!=null && values.length>0) { |
51 | 0 | Arrays.sort(values, REVERSE_COMPARE); |
52 | |
} |
53 | 0 | } |
54 | |
|
55 | |
public NameSet(Class<V> clss, Collection<? extends V> workValues) { |
56 | 0 | this(collectionToArray(clss, workValues)); |
57 | 0 | } |
58 | |
|
59 | |
private static <D extends HasName> D[] collectionToArray(Class<D> collectionType, Collection<? extends D> workValues) { |
60 | 0 | if(workValues.isEmpty()) { |
61 | 0 | return null; |
62 | |
} |
63 | |
@SuppressWarnings("unchecked") |
64 | 0 | D[] newInstance = (D[]) Array.newInstance(collectionType, workValues.size()); |
65 | 0 | return workValues.toArray(newInstance); |
66 | |
} |
67 | |
|
68 | |
public V getValue(final String name) { |
69 | 0 | int idx= Arrays.binarySearch(values, new HasName() { |
70 | |
@Override |
71 | |
public String getName() { |
72 | 0 | return name; |
73 | |
} |
74 | |
}, REVERSE_COMPARE); |
75 | 0 | return idx<0 ? null : values[idx]; |
76 | |
} |
77 | |
|
78 | |
private static interface NameResolve extends HasName, HasResolve {}; |
79 | 0 | private static NameSet<NameResolve> EMPTY_SET = new NameSet<NameResolve>(new NameResolve[0]); |
80 | |
|
81 | |
public static <V extends HasName & HasResolve> NameSet<V> emptyNameSet() { |
82 | 0 | NameSet<?> qrc = (NameSet<?>) EMPTY_SET; |
83 | |
@SuppressWarnings("unchecked") |
84 | 0 | NameSet<V> rc = (NameSet<V>) qrc; |
85 | 0 | return rc; |
86 | |
} |
87 | |
} |