java反射中方法的调用
摘抄:
java反射是要解析字节码,将内存中的对象进行解析,包括了一些动态类型,所以JVM无法对这些代码进行优化。因此,反射操作的效率要比那些非反射操作低得多!
反射:
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制
public class Test { public static void main(String[] args) throws InstantiationException, IllegalAccessException { /* public Student(){} public void eat(){ System.out.println("吃好多的"); }*/ Class classz= Student.class; //获取的类 Student student= (Student) classz.newInstance(); //获取类中的对象 student.eat(); } }
import java.lang.reflect.Method; //私有化普通方法的时候 public class Test02 { public static void main(String[] args) throws Exception{ /* public Student(){} private void eat(){ System.out.println("吃好多的"); }*/ Class class1= Student.class; Student student= (Student) class1.newInstance();//获取类的对象 Method method= class1.getDeclaredMethod("eat"); method.setAccessible(true); method.invoke(student); } }
import java.lang.reflect.Method; //私有化的普通方法,且带有参数 public class Test03 { public static void main(String[] args) throws Exception { /* public Student(){} private void eat(String tpe){ System.out.println("吃好"+tpe+"多的"); }*/ Class clazz= Student.class; Student student= (Student) clazz.newInstance(); /*私有化的方法,有无参数的时候*/ Method method= clazz.getDeclaredMethod("eat", String.class); method.setAccessible(true);//设置那个开关 method.invoke(student,"哈哈" );//当私有化的普通方法也有参数时,在此处接受返回的参数 } }
import java.lang.reflect.Constructor; //私有化构造方法,且无参数 public class Test04 { public static void main(String[] args) throws Exception { /* private Student(){} public void eat(){ System.out.println("吃好多的"); }*/ Class clazz= Student.class; Constructor constructor= clazz.getDeclaredConstructor(); constructor.setAccessible(true); Student student= (Student) constructor.newInstance();//创建对象的方法 student.eat(); /*当构造方法是私有的,但是无参的构造方法*/ } }
import java.lang.reflect.Constructor; //私有化的构造方法是带有参数的 public class Test05 { public static void main(String[] args) throws Exception{ /* private Student(String name){ } public void eat(){ System.out.println("吃好多的"); }*/ Class clazz= Student.class; Constructor constructor= clazz.getDeclaredConstructor(String.class); constructor.setAccessible(true); Student student= (Student) constructor.newInstance("哈哈"); student.eat(); } }