您的位置:首页 > 职场人生

黑马程序员_类加载器、内省、JavaBean、BeanUtil学习笔记

2014-03-14 19:25 417 查看
------- android培训java培训、期待与您交流! ----------

类加载器部分

大部分类加载器本身就是类

1、BootStrap:不是类。是C++语言实现的。

ExtClassLoader的父节点。

管理jre/lib/rt.jar中的类。

eg:System类的加载器,对System类使用getClass(),返回值为null。

2、ExtClassLoader:

管理jre/lib/ext/*.jar中的类。专门加载jre/lib/ext/目录下,所有的jar包。

AppClassLoader的父节点

3、AppClassLoader:

管理CLASSPATH指定的所有jar目录。

eg:main函数的加载。

4、委托机制

当前线程类加载器。(线程类中,提供了上下文类加载器,通过方法getContextClassLoader()获得)

加载过程中,如果A引用B,则使用加载类A的加载器来加载B。

还可以使用ClassLoader.loadClass()来指定某个加载器去加载某个类。

5、自定义类加载器

步骤:

1)必须继承ClassLoader

2)覆盖方法findClass(),为了保留loadClass()方法中的流程。(模板方法设计模式)

3)调用defineClass()方法,将文件中的方法转换成字节码。

6、自定义类加载器的调用

Object obj = new MyClassLoader("Dir").loadClass("ClassName").newInstance();


7、用类加载器加载资源

用类加载器放在classPath指定的目录下的配置文件,eg:

1)类加载器方法:(相对于运行路径)

InputStream ips = FrameDemo.class.getClassLoader().getResourceAsStream("frame/config.properties");


2)类加载方法:(相对于类的.class文件路径)

InputStream ips = FrameDemo.class.getResourceAsStream("config.properties");


内省部分

1、内省(IntroSpector)

用于对JavaBean进行操作。

2、JavaBean是特殊的JAVA类。

符合特定规则的JAVA类,方法名以getXXX()、setXXX()命名。

VO:(Value Object)

3、使用JavaBean的get方法(用于替换Java复杂的方法调用)

ReflectPoint pt1 = new ReflectPoint(3,5);
String propertyName = "x";
PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());    //<--参数为:属性名,类字节码。(获取属性内省器)
Method method = pd.getReadMethod();//<--获取读方法
Object returnVal  = method.invoke(pt1, null);


4、使用JavaBean的set方法(用于替换Java复杂的方法调用)

ReflectPoint pt1 = new ReflectPoint(3,5);
String propertyName = "x";
PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());   //<--参数为:属性名,类字节码。(获取属性内省器)
Method method = pd.getWriteMethod();            //<--获取写方法
Object returnVal  = method.invoke(pt1, 7);


*、Eclipse中的代码重构

简单方法

1)选中需要被重构封装的代码

2)右键 -> Refactor -> Extract Method

5、复杂内省操作

BeanInfo bi = Introspector.getBeanInfo(pt1.getClass());     //<--获取整个JavaBean的信息
PropertyDescriptor[] pds = bi.getPropertyDescriptors();     //<--获取属性内省器集合
for(PropertyDescriptor pd : pds)
{
if(pd.getName().equals("x"))                //<--找到名称为x的属性
{
Method method = pd.getWriteMethod();
method.invoke(pt1,"newValue");
}
}


6、BeanUtils(Apache提供的工具类)

以字符串的形式对JavaBean进行操作。

简单的get、set,eg:

BeanUtils.getProperty(pt1, "x");
BeanUtils.setProperty(pt1, "x", 9);
级联的get、set,eg:

BeanUtils.setProperty(pt1, "birthday.time", 111);       //<--birthday为Date类实例


7、PropertyUtils

以属性本身的类型进行操作。功能与BeanUtils类似。-------
android培训、java培训、期待与您交流! ----------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: