2 * Copyright (C) 2014, United States Government, as represented by the
3 * Administrator of the National Aeronautics and Space Administration.
6 * The Java Pathfinder core (jpf-core) platform is licensed under the
7 * Apache License, Version 2.0 (the "License"); you may not use this file except
8 * in compliance with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0.
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 package gov.nasa.jpf.util;
20 import gov.nasa.jpf.JPFException;
22 import java.lang.reflect.InvocationTargetException;
23 import java.lang.reflect.Method;
24 import java.lang.reflect.Modifier;
27 * reflection utilities
29 public class Reflection {
34 * @param up levels upwards from our caller (NOT counting ourselves)
35 * @return caller class, null if illegal 'up' value
37 public static Class<?> getCallerClass(int up) {
38 int idx = up + 1; // don't count this stackframe
40 StackTraceElement[] st = (new Throwable()).getStackTrace();
41 if ((up < 0) || (idx >= st.length)) {
45 return Class.forName(st[idx].getClassName());
46 } catch (Throwable t) {
52 public static Class<?> getCallerClass () {
53 return getCallerClass(2);
56 public static <T> Class<? extends T> getCallerClass (Class<T> type){
57 Class<?> cls = getCallerClass(2);
60 if (type.isAssignableFrom(cls)) {
61 return cls.asSubclass(type);
63 throw new JPFException("caller class: " + cls.getName() + " not of type: " + type.getName());
69 public static StackTraceElement getCallerElement (int up){
70 int idx = up + 1; // don't count this stackframe
72 StackTraceElement[] st = (new Throwable()).getStackTrace();
73 if ((up < 0) || (idx >= st.length)) {
79 public static StackTraceElement getCallerElement () {
80 StackTraceElement[] st = (new Throwable()).getStackTrace();
82 return st[2]; // '0' is this method itself
88 public static boolean tryCallMain(Class<?> cls, String[] args) throws InvocationTargetException {
90 Method method = cls.getDeclaredMethod("main", String[].class);
91 int modifiers = method.getModifiers();
93 if ((modifiers & (Modifier.PUBLIC | Modifier.STATIC | Modifier.ABSTRACT)) == (Modifier.PUBLIC | Modifier.STATIC)) {
94 method.invoke(null, (Object)args);
98 } catch (NoSuchMethodException nsmx) {
99 //System.out.println(nsmx);
101 } catch (IllegalAccessException iax){
102 //System.out.println(iax);
103 // can't happen, we checked for it before invoking
104 } catch (IllegalArgumentException iargx){
105 //System.out.println(iargx);
106 // can't happen, we checked for it before invoking