Created
November 1, 2012 22:08
-
-
Save volgar1x/3996991 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 org.shivas.core; | |
import junit.framework.TestCase; | |
import java.lang.annotation.*; | |
import java.lang.reflect.Field; | |
import java.util.*; | |
public class Test extends TestCase { | |
@Retention(value = RetentionPolicy.RUNTIME) | |
@Target(value = {ElementType.FIELD}) | |
static @interface Config { | |
String key(); | |
} | |
static class Configured { | |
@Config(key="client.version") | |
private static String CLIENT_VERSION; | |
@Config(key="login.port") | |
private static short LOGIN_PORT; | |
} | |
@Override | |
protected void setUp() throws Exception { | |
Configured.CLIENT_VERSION = null; | |
} | |
private List<Class<?>> getClasses(ClassLoader classLoader) throws ReflectiveOperationException { | |
Class<?> clazz = classLoader.getClass(); | |
while (clazz != ClassLoader.class) { | |
clazz = clazz.getSuperclass(); | |
} | |
Field field = clazz.getDeclaredField("classes"); | |
field.setAccessible(true); | |
return new ArrayList<Class<?>>((Collection<Class<?>>) field.get(classLoader)); | |
} | |
private void injectConfigValues(Map<String, Object> configValues) throws ReflectiveOperationException { | |
for (Class<?> clazz : getClasses(Thread.currentThread().getContextClassLoader())) { | |
for (Field field : clazz.getDeclaredFields()) { | |
Config annotation = field.getAnnotation(Config.class); | |
if (annotation == null) continue; | |
Object value = configValues.get(annotation.key()); | |
if (value == null) { | |
System.out.format("unknown config value \"%s\" in class %s\n", annotation.key(), clazz.getCanonicalName()); | |
} else { | |
if (!field.isAccessible()) { | |
field.setAccessible(true); | |
} | |
field.set(null, value); | |
} | |
} | |
} | |
} | |
public void test1() { | |
try { | |
injectConfigValues(new HashMap<String, Object>() {{ | |
put("client.version", "1.29.1"); | |
put("login.port", (short) 5555); | |
}}); | |
} catch (ReflectiveOperationException e) { | |
e.printStackTrace(); | |
} | |
assertEquals("1.29.1", Configured.CLIENT_VERSION); | |
assertEquals(5555, Configured.LOGIN_PORT); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment