JAVA基础--JAVA中的反射机制详解
转贴:http://java.ccidnet.com/art/3539/20070924/1222147_1.html
JAVA反射机制
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
Java反射机制主要提供了以下功能: 在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。
1. 得到某个对象的属性
1 public Object getProperty(Object owner, String fieldName) throws Exception {
2 Class ownerClass = owner.getClass();
3
4 Field field = ownerClass.getField(fieldName);
5
6 Object property = field.get(owner);
7
8 return property;
9 }
Class ownerClass = owner.getClass():得到该对象的Class。
Field field = ownerClass.getField(fieldName):通过Class得到类声明的属性。
Object property = field.get(owner):通过对象得到该属性的实例,如果这个属性是非公有的,这里会报IllegalAccessException。
2. 得到某个类的静态属性
1 public Object getStaticProperty(String className, String fieldName)
2 throws Exception {
3 Class ownerClass = Class.forName(className);
4
5 Field field = ownerClass.getField(fieldName);
6
7 Object property = field.get(ownerClass);
8
9 return property;
10 }
Class ownerClass = Cla
相关文档:
今天遇到一个很诡异的bug,调试了半天也没有看出来有什么问题,抽象一下代码如下:
public class Instance
{
public static Instance instance = new Instance();
public static Map<String, String> map = new HashMap<String, String>();
public static Instance instance()
{
r ......
http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp
Categories of Java HotSpot VM Options
Standard options recognized by the Java HotSpot VM are described on the Java Application Launcher reference pages for Windows
, Solaris
and Linux
. This document deals exclusively wit ......
1、Oracle8/8i/9i数据库(thin模式)
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl"; //orcl为数据库的SID
String user="test";
String password="test";
Connection conn= DriverManager.getC ......
JAVA开发者最常去的20个英文网站
2009年09月01日 09:56 分类:Java资讯 浏览: 33,388 次
JAVA开发者最常去的20个英文网站
1.[http://www.javaalmanac.com] – Java开发者年鉴一书的在线版本. 要想快速查到某种Java技巧的用法及示例代码, 这是一个不错的去 ......