JAVA_Reflection1
package com.qf.reflection1; import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method; class Student {
private String name;
private int age; public String getName() {
return name;
} private void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public Student(String name, int age) {
super();
this.name = name;
this.age = age;
} public Student() {
super();
} } public class Test { public static void main(String[] args) { try {
// 使用反射第一步 得到某个类的Class对象
Class<Student> clazz1 = Student.class;
Class<?> clazz2 = Class.forName("com.qf.reflection1.Student");
Student student = new Student();
Class<?> clazz3 = student.getClass(); System.out.println("访问类所有属性");
// clazz1.getDeclaredField("age");// 根据属性名 得到属性值 私有的也能得到
// clazz1.getField("name");// 只能得到有访问权限的指定属性
// clazz1.getFields();//得到有访问权限的所有属性
Field fields[] = clazz1.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
} // 通过反射创建Student对象
// 1,得到无参构造方法
Constructor<Student> constructor = clazz1.getConstructor();
// 2,创建对象
Student stu = constructor.newInstance();
// 等价于 Student stu = new Student(); // 调用setName
// 1,得到setName()
Method method = clazz1.getDeclaredMethod("setName", new Class[] { String.class });
// 私有方法需要设置访问权限
method.setAccessible(true);
// 2,通过之前的student对象调用setName表示的方法
method.invoke(stu, new Object[] { "尼古拉斯赵四" }); // 1,得到getName()
Method getName = clazz1.getDeclaredMethod("getName", new Class[] {});
// 2,通过之前的student对象调用getName表示的方法
Object object = getName.invoke(stu, new Object[] {});
System.out.println(object); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
JAVA_Reflection1的更多相关文章
随机推荐
- java web接收POST数据
新建一个ServerForPOSTMethod的动态网站工程
- linux操作系统cp命令
- 0R电阻作用
0欧电阻的作用(网上收集整理的) 0欧的电阻大概有以下几个功能: ①做为跳线使用.这样既美观,安装也方便. ②在数字和模拟等混合电路中,往往要求两个地分开,并且单点连接.我们可以用一个0欧的电阻来 ...
- adb 启动失败的原因和修改adb端口号
在我们使用Android Studio的时候,有时候就会出现adb打开失败或者启动不了的情况. adb 启动失败的原因:有其他程序占用了adb默认启动的端口号(像我就遇到过,每次只要提前启动了酷狗音乐 ...
- Linq to Sql 总生成 where ID is null 的解决办法
using (Entities com = new Entities()){ com.Configuration.UseDatabaseNullSemantics = true; } EF+M ...
- class-dump 复制到/usr/bin目录不可写,Operation not permitted 解决办法
许多升级了OSX 10.11的朋友在配置class-dump的时候,会发现书上推荐的class-dump存放目录/usr/bin不再可写,如下所示: Operation not permitted 把 ...
- 编写Qt Designer自定义控件(二)——编写自定义控件界面
接上文:编写Qt Designer自定义控件(一)——如何创建并使用Qt自定义控件 既然是控件,就应该有界面,默认生成的控件类只是一个继承了QWidget的类,如下: #ifndef LOGLATED ...
- SpringMVC(二)
今天在完成的工作的前提下,最终在睡觉前将SpringMVC和Mybatis整合了~~~ 其实就是按照从网上(参考http://www.toutiao.com/a6332703083554324737/ ...
- SQL Server 重新恢复自动编号列的序号
1. truncate table tablename2. DBCC CHECKIDENT (tablename,reseed,1) truncate命令不但会清除所有的数据,还会将IDENTIT ...
- zabbix 3.0 安装
zabbix3.0安装注意: 1.PHP要5.4版本以上 2.防火墙关闭 3.selinux关闭 注:本操作系统为centos 6.5 X86 操作步骤 一.安装PHP 添加 epel 源 # r ...