一. 创建一个简单的java类如下:
package cn.zq;
public class SomeClass {
/**
* 转换成小写
**/
public void toLower(String s)
{
System.out.println("toLower方法");
System.out.println("原字符:"+s);
System.out.println("转换后:"+s.toLowerCase()) ;
}
/**
* 转换成大写
**/
public void toUpper(String s)
{
System.out.println("toUpper方法");
System.out.println("原字符:"+s);
System.out.println("转换后:"+s.toUpperCase()) ;
}
}
二. 创建反射类
package cn.zq;
import java.lang.reflect.InvocationTargetException;
public class TestRefl {
public void test1(String action) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
SecurityException,
NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException
{
Class clazz = Class.forName(action);
SomeClass c = (SomeClass) clazz.newInstance();
c.toUpper("ffff");
c.toLower("AAAA");
}
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
SecurityException,
NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException
{
TestRefl tr = new TestRefl();
tr.test1("cn.zq.SomeClass");
}
}
结果如图
反射类也可以写成如下
package cn.zq;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestRefl {
public void test1(String action) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
SecurityException,
NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException
{
Class clazz = Class.forName(action);
SomeClass c = (SomeClass) clazz.newInstance();
Method m = clazz.getMethod("toLower", new Class[]{String.class});
m.invoke(c, new Object[]{"STR"});
Method m2 = clazz.getMethod("toUpper", new Class[]{String.class});
m2.invoke(c, new Object[]{"str"});
}
public static void main(String[] args) throws ClassNotFoundException,
InstantiationException,
IllegalAccessException,
SecurityException,
NoSuchMethodException,
IllegalArgumentException,
InvocationTargetException
{
TestRefl tr = new TestRefl();
tr.test1("cn.zq.SomeClass");
}
}
结果如下