zoukankan      html  css  js  c++  java
  • java反射详解 一

    【案例1】通过一个对象获得完整的包名和类名

    package Reflect;

    /**
    * 通过一个对象获得完整的包名和类名
    * */
    class Demo{
    //other codes...
    }

    class hello{
    public static void main(String[] args) {
    Demo demo=new Demo();
    System.out.println(demo.getClass().getName());
    }
    }


    【运行结果】:Reflect.Demo

    添加一句:所有类的对象其实都是Class的实例。

    【案例2】实例化Class类对象

    package Reflect;
    class Demo{
    //other codes...
    }

    class hello{
    public static void main(String[] args) {
    Class<?> demo1=null;
    Class<?> demo2=null;
    Class<?> demo3=null;
    try{
    //一般尽量采用这种形式
    demo1=Class.forName("Reflect.Demo");
    }catch(Exception e){
    e.printStackTrace();
    }
    demo2=new Demo().getClass();
    demo3=Demo.class;

    System.out.println("类名称 "+demo1.getName());
    System.out.println("类名称 "+demo2.getName());
    System.out.println("类名称 "+demo3.getName());

    }
    }


    【运行结果】:

    类名称   Reflect.Demo

    类名称   Reflect.Demo

    类名称   Reflect.Demo

    【案例3】通过Class实例化其他类的对象

    通过无参构造实例化对象

    package Reflect;

    class Person{

    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;
    }
    @Override
    public String toString(){
    return "["+this.name+" "+this.age+"]";
    }
    private String name;
    private int age;
    }

    class hello{
    public static void main(String[] args) {
    Class<?> demo=null;
    try{
    demo=Class.forName("Reflect.Person");
    }catch (Exception e) {
    e.printStackTrace();
    }
    Person per=null;
    try {
    per=(Person)demo.newInstance();
    } catch (InstantiationException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IllegalAccessException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    per.setName("Rollen");
    per.setAge(20);
    System.out.println(per);
    }
    }


    【运行结果】:

    [Rollen  20]


    全文请看 http://www.cnblogs.com/rollenholt/archive/2011/09/02/2163758.html
  • 相关阅读:
    source insight 使用介绍
    android 自定义progressBar
    appium环境安装
    js定义类的三种方法
    对象,函数,构造函数this,原型
    mindjet使用技巧
    在wamp下安装bugfree
    QTP
    powerdesigner使用
    随笔
  • 原文地址:https://www.cnblogs.com/hangaozu/p/7544473.html
Copyright © 2011-2022 走看看