您的位置:首页 > 编程语言 > Java开发

Java 反射机制 .class .getClass() Class.forName("") .TYPE int void

2016-02-23 09:47 609 查看
package com.age.www;

public class ReflectionDemo {

public static void main(String[] args)  {
//对象名.getClass()产生Class对象
Emploree1 e=new Emploree1();
Class<?> emploree=e.getClass();
System.out.println(emploree.getName());
//Class.forName("")静态方法:
try {
try {
Emploree1 emp1=(com.age.www.Emploree1)Class.forName("com.age.www.Emploree1").newInstance();
emp1.tell();
} catch (InstantiationException | IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// .class直接生成Class对象
try {
Emploree1.class.newInstance().tell();
} catch (InstantiationException | IllegalAccessException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

//8中包装类的.TYPE属性  也报错8中基本类型都可以用.class ...表示基本类型double int 等实例。 没有父类,就是基本类型实例。 不能有newInstance方法。
//System.out.println(Boolean.TYPE.getSuperclass().getName());
Class cl=Boolean.TYPE;
Class<?> c2=Double.TYPE;
//c2.newInstance();
//System.out.println(c2.getSuperclass());
System.out.println("Double.TYPE.getName()  "+Double.TYPE.getName());
System.out.println("Double.class.getName()  "+Double.class.getName());
Class c3=Double.class;   // .class总能找到父类,基本是基本数据类型的包装类型。
System.out.println(c3.getSuperclass().getName());

// try {

// //Number n1=(Number)c2.newInstance();

//

//

// //Boolean bl=(Boolean)cl.newInstance();

// //System.out.println(bl.toString());

// //System.out.println(bl.hashCode());

// } catch (InstantiationException | IllegalAccessException e1) {

// // TODO Auto-generated catch block

// e1.printStackTrace();

// }

}

}

class Emploree1 {

private String name="zhangsan";
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
private int age=20;

public void tell(){

System.out.println(name+age);
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 反射 .class Class