public class ConfigReader { public static void main(String[] args) { try { Properties properties = new Properties(); properties.load(ConfigReader.class.getClassLoader().getResourceAsStream("config.properties")); Class<?> clazz = Class.forName(properties.getProperty("class.name")); Object instance = clazz.getDeclaredConstructor().newInstance(); Field field = clazz.getDeclaredField(properties.getProperty("field.name")); field.setAccessible(true); field.set(instance, properties.getProperty("new.field.value")); } catch (Exception e) { e.printStackTrace(); } } } class.name=com.example.Config field.name=configValue new.field.value=New Value import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; interface Hello { void sayHello(); } class HelloImpl implements Hello { @Override public void sayHello() { System.out.println("Hello, World!"); } } public class DynamicProxyExample { public static void main(String[] args) { Hello hello = (Hello) Proxy.newProxyInstance( DynamicProxyExample.class.getClassLoader(), new Class[]{Hello.class}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before method invocation..."); Object result = method.invoke(new HelloImpl(), args); System.out.println("After method invocation..."); return result; } }); hello.sayHello(); } } import java.lang.reflect.Field; class MyClass { private String privateField = "privateValue"; public void setPrivateField(String privateField) { this.privateField = privateField; } public String getPrivateField() { return privateField; } } public class ReflectionTestUtils { public static void main(String[] args) { MyClass obj = new MyClass(); try { Field field = MyClass.class.getDeclaredField("privateField"); field.setAccessible(true); field.set(obj, "newValue"); } catch (Exception e) { e.printStackTrace(); } obj.setPrivateField("anotherNewValue"); } }


上一篇:
下一篇:
切换中文