文章标题
来源:互联网 发布:老人去世无人知 编辑:程序博客网 时间: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
- 文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题 文章标题 文章标题 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 文章标题
- 【HDU5816】Hearthstone(状压DP)
- Boost基础学习
- EasyUI数据分页实现(真假分页)
- 简单客户端 服务端代码
- php CGI、Fastcgi、PHP-FPM的详细介绍与之间的关系
- 文章标题
- java中form以post、get方式提交数据中文乱码问题总结
- 封装windows 线程创建函数_beginthreadex和createthread函数的类
- TreeMap详细介绍(源码解析)和使用示例
- grep命令详解
- uva10200
- POJ 1386-Play on Words(有向欧拉通路)
- Android简易实战教程--第十七话《自定义彩色环形进度条》
- [leetcode] 64. Minimum Path Sum