反射

来源:互联网 发布:java 无效的源版本1.9 编辑:程序博客网 时间:2024/06/07 12:00

1,.如何通过反射创建对象

- 方法1:通过类对象调用newInstance()方法,例如:String.class.newInstance() 
- 方法2:通过类对象的getConstructor()或getDeclaredConstructor()方法获得构造器(Constructor)对象并调用其newInstance()方法创建对象,例如:String.class.getConstructor(String.class).newInstance("Hello");

2.如何通过反射调用对象的方法? 

  1. import java.lang.reflect.Method;  
  2. class MethodInvokeTest {     
  3.  public static void main(String[] args) throws Exception {      
  4.     String str = "hello";         
  5.  Method m = str.getClass().getMethod("toUpperCase");       
  6.    System.out.println(m.invoke(str));  
  7.   // HELLO     
  8.  }  
  9. }  
3.反射的基本要素:我的面试题,找不到答案

0 0