java反射

package com.bankcomm.member.online.commons;


import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


public class ReflectDemo {
//Employee emp = new Employee();
@SuppressWarnings({ "unchecked"})
public static void main(String[] args) throws ClassNotFoundException, SecurityException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Class cl = Class.forName("com.bankcomm.member.online.commons.Employee");
//Class  cl = Employee.class;
/*Employee ee = new Employee();
Class  cl = ee.getClass();*/
try {
/*Class  cl2 = Employee.class;
Employee ee = new Employee();
Class  cl3 = ee.getClass();
System.out.println(cl);
System.out.println(cl2);
System.out.println(cl3);*/
//Class clas = cl.getClass();
//System.out.println(clas.getClass());
/*Method[] methods = cl.getMethods();
for(Method m:methods){
//System.out.println(m);
}*/
Field field = cl.getDeclaredField("num");
field.setAccessible(true);
Object o = cl.newInstance();
field.setInt(o, 33);
System.out.println("num:----------->"+field.get(o));
Method method = cl.getDeclaredMethod("printStr", new Class[]{ String.class });
//不设置,调用另一个类的私有方法就会报错
method.setAccessible(true);
/*Method method1 = cl.getDeclaredMethod("printStr", new Class[] { String.class });
System.out.println(method);
System.out.println(method1);
Method method2 = cl.getMethod("setAge", new Class[] { int.class });
System.out.println(method2);*/
//Object[] obj = { new Integer(22) };
//Class[] argsClass = new Class[22];
//Object newObj = method.invoke(cl, new String[]{"李强"});
String printStr = (String)method.invoke(cl, new String[]{"李强"});
//System.out.println("name:------------->"+newObj);
//System.out.println("name:------------->"+printStr.getClass());
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
System.out.println(e.getMessage());
}finally{
System.out.println("代码执行结束.....");
}
}

}

------------------------------

package com.bankcomm.member.online.commons;


public class Employee {
static int age;
private int num = 22;
static String name;
// 定义一个员工类  
public Employee() {
 age = 0;
 name = null;
}
public static int getAge() {
return age;
}
public static void setAge(int age) {
Employee.age = age;
}
public static String getName() {
return name;
}
public static void setName(String name) {
Employee.name = name;
}
private static String printStr(String name){
System.out.println("name:---------->"+name);
return  name;
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值