package com.wkcto.chapter08.demo02;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
/**
* 通过反射调用方法
* method.invoke( 实例名, 方法的实参列表)
* 如果是静态方法, 实例名位置传递null
* @author 蛙课网
*
*/
public class Test03 {
public static void main(String[] args) throws Exception {
//1)创建Class对象
Class<?> class1 = String.class;
//2) 通过Class对象创建实例
Object str1 = class1.newInstance(); //new String();
//通过构造方法创建实例, String( byte[] ) 根据字节数组创建字符串
Constructor<?> constructor = class1.getConstructor( byte[].class );
byte[] bytes = "wkcto".getBytes(); //返回字符串对应的字节数组
Object str2 = constructor.newInstance(bytes);
//3)反射length()方法
Method lengthM = class1.getMethod("length");
//方法调用, invoke( 实例名, 该方法的实参列表)
Object len = lengthM.invoke(str1, null); //str1.length()
System.out.println( len );
len = lengthM.invoke(str2);
System.out.println( len );
//4)反射equals(Object)
Method equalsM = class1.getMethod("equals", Object.class);
Object result = equalsM.invoke(str1, str2); //str1.equals(str2)
System.out.println( result );
//5)反射substring( int, int )
Method substringM = class1.getMethod("substring", int.class, int.class);
Object sub = substringM.invoke(str2, 0,2); //str2.substring(0,2)
System.out.println( sub );
//6)反射静态方法 valueOf(int)
Method valueOfM = class1.getMethod("valueOf", int.class);
Object text = valueOfM.invoke(null, 258);
System.out.println( text instanceof String );
}
}