001/** 002 * This file is part of LEAP. 003 * 004 * LEAP was implemented as a plugin of DL-Learner http://dl-learner.org, 005 * but some components can be used as stand-alone. 006 * 007 * LEAP is free software; you can redistribute it and/or modify 008 * it under the terms of the GNU General Public License as published by 009 * the Free Software Foundation; either version 3 of the License, or 010 * (at your option) any later version. 011 * 012 * LEAP is distributed in the hope that it will be useful, 013 * but WITHOUT ANY WARRANTY; without even the implied warranty of 014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 015 * GNU General Public License for more details. 016 * 017 * You should have received a copy of the GNU General Public License 018 * along with this program. If not, see <http://www.gnu.org/licenses/>. 019 * 020 */ 021package org.dllearner.utils.unife; 022 023import java.lang.reflect.Field; 024 025/** 026 * Utility class that uses reflection to get values of private fields and 027 * methods during the test phase. 028 * 029 * @author Giuseppe Cota <giuseppe.cota@unife.it> 030 */ 031public class ReflectionHelper { 032 033 public static <T, E> T getPrivateField(E instance, Class<T> returnType, String fieldName) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { 034 Field privateField = instance.getClass().getDeclaredField(fieldName); 035 privateField.setAccessible(true); 036 T value = (T) privateField.get((E) instance); 037 return value; 038 } 039 040 public static <T, E> T getPrivateField(E instance, String fieldName) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { 041 Field privateField = instance.getClass().getDeclaredField(fieldName); 042 privateField.setAccessible(true); 043 T value = (T) privateField.get((E) instance); 044 return value; 045 } 046 047 public static <T, E> void setPrivateField(E instance, String fieldName, T value) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { 048 Field privateField = instance.getClass().getDeclaredField(fieldName); 049 privateField.setAccessible(true); 050 privateField.set(instance, value); 051 } 052 053 public static <T, E> T getPrivateStaticField(Class<E> clazz, Class<T> returnType, String fieldName) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { 054 Field privateField = clazz.getDeclaredField(fieldName); 055 privateField.setAccessible(true); 056 T value = (T) privateField.get(null); 057 return value; 058 } 059 060 public static <T, E> T getPrivateStaticField(Class<E> clazz, String fieldName) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException { 061 Field privateField = clazz.getDeclaredField(fieldName); 062 privateField.setAccessible(true); 063 T value = (T) privateField.get(null); 064 return value; 065 } 066 067}