Created
September 22, 2013 07:52
-
-
Save firstspring1845/6657747 to your computer and use it in GitHub Desktop.
リフレクションするやつ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.firstspring.lib; | |
import java.lang.reflect.Field; | |
import java.lang.reflect.Method; | |
public class ReflectionUtil | |
{ | |
@SuppressWarnings("unchecked") | |
public static <T,E> E getField(Class<?> c, T instance, String field) | |
{ | |
try | |
{ | |
Field f = c.getDeclaredField(field); | |
f.setAccessible(true); | |
return (E)f.get(instance); | |
} | |
catch(Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
public static <T,E> E getField(T instance, String field) | |
{ | |
return getField(instance.getClass(), instance, field); | |
} | |
public static <T,E> boolean setField(Class<?> c, T instance, String field, E value) | |
{ | |
try | |
{ | |
Field f = c.getDeclaredField(field); | |
f.setAccessible(true); | |
f.set(instance, value); | |
return true; | |
} | |
catch(Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
return false; | |
} | |
public static <T,E> boolean setField(T instance, String field, E value) | |
{ | |
return setField(instance.getClass(), instance, field, value); | |
} | |
public static Method getMethod(Class<?> c, String method, Class<?>... argTypes) | |
{ | |
try | |
{ | |
Method m = c.getDeclaredMethod(method, argTypes); | |
m.setAccessible(true); | |
return m; | |
} | |
catch(Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
@SuppressWarnings("unchecked") | |
public static <T,E> E invoke(T instance, Method m, Object... args) | |
{ | |
try | |
{ | |
return (E)m.invoke(instance, args); | |
} | |
catch(Exception e) | |
{ | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment