01 /*
02 * Java Genetic Algorithm Library (jenetics-3.5.0).
03 * Copyright (c) 2007-2016 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
19 */
20 package org.jenetics.internal.util;
21
22 import static java.util.Arrays.stream;
23 import static java.util.stream.Stream.concat;
24
25 import java.util.Optional;
26 import java.util.stream.Stream;
27
28 import org.jenetics.util.ISeq;
29
30 /**
31 * Helper methods concerning Java reflection.
32 *
33 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
34 * @since 1.6
35 * @version 3.0
36 */
37 public class reflect {
38 private reflect() {require.noInstance();}
39
40 /**
41 * Return all declared classes of the given class, with arbitrary nested
42 * level.
43 *
44 * @param cls the class for which the declared classes are retrieved.
45 * @return all nested classes
46 */
47 public static Stream<Class<?>> innerClasses(final Class<?> cls) {
48 return concat(
49 stream(cls.getDeclaredClasses()).flatMap(reflect::innerClasses),
50 stream(cls.getDeclaredClasses())
51 );
52 }
53
54 /**
55 * Return the class of the given value or the value if it is already from
56 * the type {@code Class}.
57 *
58 * @param value the value to get the class from.
59 * @return the class from the given value, or {@code value} if it is already
60 * a {@code Class}.
61 */
62 public static Class<?> classOf(final Object value) {
63 return value instanceof Class<?> ? (Class<?>)value : value.getClass();
64 }
65
66 @SuppressWarnings("unchecked")
67 public static <T> Optional<T> newInstance(final Class<?> type) {
68 try {
69 return Optional.of((T)type.newInstance());
70 } catch (InstantiationException | IllegalAccessException e) {
71 return Optional.empty();
72 }
73 }
74
75 @SuppressWarnings("unchecked")
76 public static <A, B extends A> ISeq<A> cast(final ISeq<B> seq) {
77 return (ISeq<A>)seq;
78 }
79 }
|