文章标题

来源:互联网 发布:老人去世无人知 编辑:程序博客网 时间:2024/06/07 16:10

关于反射、接口的一个小例子,只是记录。

package keepmind;//实现了Comparable接口,用于比较salarypublic class Employee implements Comparable<Employee>{    private double salary ;    private double bonus;    //注意最好留有无参构造方法    public Employee(){    }    public Employee(double salary,double bonus){        this.salary = salary;        this.bonus = bonus;    }    public double getSalary(){        return this.salary;    }    public void setSalary(double salary) {        this.salary = salary;    }    public double getBonus() {        return bonus;    }    public void setBonus(double bonus){        this.bonus = bonus;     }    public double getTotalSalary(){        return getSalary() + this.bonus;    }    //实现comparable接口中的compareTo方法    public int compareTo(Employee other){        return Double.compare(salary, other.salary);    }}

下面是继承employee的Manager类

package keepmind;import java.lang.reflect.Method;import java.util.Arrays;public class Manager extends Employee{    private String name ;    private int age;    public Manager(String name, int age, double salary, double bnous) {        super(salary,bnous);//调用父类的构造方法        this.name = name;        this.age = age;     }    public String toString(){        return getClass().getName();    }    public static void main(String[] args) throws Exception {        Employee[] staff = new Employee[3];        staff[0] = new Employee(1,2);        staff[1] = new Employee(4,4);        staff[2] = new Employee(3,5);        Arrays.sort(staff);        for(Employee e : staff){            System.out.println(e.getSalary()+" , "+e.getBonus());        }        //--------------------------------        //利用反射调用方法,并且实现setter和getter方法,很好的一个例子        Class<?> demo = null;        Object obj = null;        try{            demo = Class.forName("keepmind.Employee");            obj = demo.newInstance();        }catch(Exception e){            e.printStackTrace();        }        setter(obj,"Salary",500, double.class);         getter(obj,"Salary");    }    public static void setter(Object obj, String str, Object value, Class<?> type){        try{            //getMethod需要提供对应的类类型,确保安全性,而在getter中不需要提供,合理            Method method = obj.getClass().getMethod("set"+str, type);            method.invoke(obj, value);        }catch(Exception e){            e.printStackTrace();        }    }    public static void getter(Object obj, String str){        try{            Method method = obj.getClass().getMethod("get"+str);            System.out.println(method.invoke(obj));        }catch(Exception e){            e.printStackTrace();        }    }}
0 0
原创粉丝点击