java反射spring中应用
java三种获得Class对象的方式
1.对象.getClass();
2.Class.forName("全路径");
3.类.class
package com.luchao.demo;
public class demo1 {
public static void main(String[] args) {
Class<?> d1=new demo1().getClass(); //第一种
Class<?> d2=null;
try {
d2=Class.forName("com.luchao.demo.demo1");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Class<?> d3 = demo1.class;
System.out.println(d1.getName());
System.out.println(d2.getName());
System.out.println(d3.getName());
}
}
输出:
com.luchao.demo.demo1
com.luchao.demo.demo1
com.luchao.demo.demo1
通过newInstance()实例化对象
demo1 dd=(demo1)d1.newInstance();
----------------------Spring使用------------------------
public class Person{
private String name;
public void setName(String name){
this.name=name;
}
public void info(){
System.out.println("此人名为"+name);
}
}
spring配置文件配置
<bean id="person" class="lee.Person">
<property name="name" value="wawa">
</bean>
实例化对象
Person p = (Person)ctx.getBean("person");
p.info();
|
|