这篇文章将为大家详细讲解有关java 中反射简单使用示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
package reflect_test;public class Dog implements Animals { private int age =100; private String xstr="test..."; public int page = 100000;private Dog(String xstr) { this.xstr = xstr; } public Dog() { } public Dog(int age) { this.age = age; }@Overridepublic String scrime(String str) {return str;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}private int getAddAge() {return age+=10;}public void getXstr() {System.out.println(xstr);}}----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------测试类:package reflect_test;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import org.junit.Before;import org.junit.Test;public class TestDemo {Class<?> clazz= null;Class<?> interfa = null;Object obj = null;@Beforepublic void init() throws ClassNotFoundException, InstantiationException, IllegalAccessException {clazz = Class.forName("reflect_test.Dog");interfa = Class.forName("reflect_test.Animals");obj = clazz.newInstance(); }//调用非私有成员函数@Testpublic void MethodTest() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {Method m = clazz.getMethod("scrime", String.class);Object object = m.invoke(obj, "say.....");System.out.println(object);}//调用私有成员函数@Testpublic void privateMethodTest() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {Method m = clazz.getDeclaredMethod("getAddAge");m.setAccessible(true);Object object = m.invoke(obj);System.out.println(object);}//获取非私有构造函数@Testpublic void getNotPrivateConstructor() throws Exception {Constructor<?> construct = clazz.getConstructor(int.class);Dog dog = (Dog)construct.newInstance(10);System.out.println("The age is : "+dog.getAge());}//获取私有构造函数@Testpublic void getPrivateConstructor() throws Exception {//该出方法与非私有构造器区别getDeclaredConstructorConstructor<?> construct = clazz.getDeclaredConstructor(String.class);//获得权限construct.setAccessible(true);Dog dog = (Dog)construct.newInstance("1000");dog.getXstr();}//获取非私有变量@Testpublic void getField() throws Exception {Field f = clazz.getDeclaredField("age");f.setAccessible(true);Object value = f.get(obj);System.out.println(value);}//获取私有变量@Testpublic void getPirvateField() throws Exception {Field f = clazz.getField("page");Object value = f.get(obj);System.out.println(value);}}
关于“java 中反射简单使用示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。