JAVA反射---类的继承与派生

在这里插入图片描述

package com.a.entity;

public class Circle extends TwoDShape {
	private double r;	
	@Override
	public double getArea() {
		return Math.PI * r * r;
	}
	@Override
	public double getVolume() {
		return 0;
	}
}
package com.a.entity;

public class Cube extends ThreeDShape {
	private double a;
	@Override
	public double getArea() {
		return 6 * a * a ;
	}
	@Override
	public double getVolume() {
		return a * a * a;
	}
}
package com.a.entity;

public abstract class ThreeDShape extends Shape {
	@Override
	public abstract double getArea();
	@Override
	public abstract double getVolume();
}
package com.a.entity;

public abstract class TwoDShape extends Shape {
	@Override
	public abstract double getArea();
}
package com.a.entity;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class ShapeCount {
	/**
	 * 获取包名 保证那些对象和这个类在同一个包下面
	 */
	private String packageName = ShapeCount.class.getPackage().getName() + ".";

	/**
	 * 把结果写到文件
	 * 
	 * @param list
	 * @param file
	 */
	public void writeShape2File(List<Shape> list, File file) {
		try (OutputStream os = new FileOutputStream(file);
				OutputStreamWriter osw = new OutputStreamWriter(os);
				BufferedWriter bw = new BufferedWriter(osw);) {

			for (Shape s : list) {
				if (s == null) {
					continue;
				}
				String area = " 面积为:" + String.format("%.2f", s.getArea());
				String volume = "";
				// 得到该类的父类
				String superClassName = s.getClass().getSuperclass().getName();
				if (superClassName.equals(ThreeDShape.class.getName())) {
					// 三维物体 计算体积
					volume = " 体积为:" + String.format("%.2f", s.getVolume());
				}
				String name = s.getClass().getSimpleName() + area + volume;
				bw.write(name);
				bw.newLine();
				bw.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 把一行数据转为Shape 对象
	 * 
	 * @param info
	 * @return
	 */
	public Shape getShape(String[] info) {
		if (info != null && info.length >= 0) {

			String className = str2ClassName(info[0]);
			if (isBank(className)) {
				return null;
			}
			try {
				Class<?> clzz = Class.forName(packageName + className);
				Object obj = clzz.newInstance();
				Field[] fs = clzz.getDeclaredFields();
				if (fs.length != info.length - 1) {
					System.out.println("物体计算参数值不对");
					return null;
				}
				for (int i = 0; i < fs.length; i++) {
					Field f = fs[i];
//					 在一个类的外面获取类中私有成员变量的值需要声明Accessible为true 否则IllegalAccessException
					f.setAccessible(true);
					// 给属性赋值
					f.set(obj, Double.valueOf(info[i + 1]));
				}
				return (Shape) obj;
			} catch (ClassNotFoundException e) {
				String str = e.getMessage();
				str = str.substring(str.lastIndexOf(".") + 1);
				System.out.println(str + "物体未定义(请保证定义类或者类在" + packageName + "下)");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	/**
	 * 从文件中读取Shape对象
	 * 
	 * @param file
	 * @return
	 */
	public List<Shape> readFileGetShape(File file) {
		try (InputStream is = new FileInputStream(file);
				InputStreamReader isr = new InputStreamReader(is);
				BufferedReader br = new BufferedReader(isr);) {
			String line = null;
			List<Shape> list = new ArrayList<Shape>();
			while ((line = br.readLine()) != null) {
				String[] info = line.split(" ");
				list.add(getShape(info));
			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 字符串判空
	 * 
	 * @param str
	 * @return
	 */
	public boolean isBank(String str) {
		return str == null || "".equals(str) || str.length() == 0;
	}

	/**
	 * 字符串转类名
	 * 
	 * @param str
	 * @return
	 */
	public String str2ClassName(String str) {

		if (isBank(str)) {
			return null;
		}

		str = str.toLowerCase();

		char firstChar = str.charAt(0);

		String firstStr = firstChar + "";

		firstStr = firstStr.toUpperCase();
		String otherStr = "";
		if (str.length() >= 2) {
			otherStr = str.substring(1);
		}
		return firstStr + otherStr;
	}
}
package com.a.entity;

public abstract class Shape {
	public abstract double getArea();
	public abstract double getVolume();
}
package com.a.entity;

import java.io.File;
import java.util.List;

public class RunMain {
	
	public static void main(String[] args) {
		ShapeCount sc = new ShapeCount();
		File file = new File("C:\\Users\\admin\\Desktop\\SV.txt");
		List<Shape> list = sc.readFileGetShape(file);
		file = new File ("C:\\Users\\admin\\Desktop\\CV.txt");
		sc.writeShape2File(list,file);
	}
}

实现结果如下
在这里插入图片描述在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值