day40
反射应用
案例
1.万能数组扩容
设置泛型的copyof仅支持引用数据类型,即任意类型,直接new数组不行,利用反射实现扩容;
打印调用toString也进行编写,利用StringBuffer或者StringBiulder进行字符串拼接
public class Test01 {
public static void main(String[] args) {
//引用数据类型
String[] ss = {"小小","大大","奇奇","怪怪","奇男子"};
String[] newSS = MyArrays.copyOf(ss, 8);
System.out.println(MyArrays.toString(newSS));
//基本数据类型
int[] is = {1,2,3,4,5};
int[] newIS = MyArrays.copyOf(is, 8);
System.out.println(MyArrays.toString(newIS));
}
}
对前面学习的数组,编写的工具类补充
/**
* 史上最牛逼的数组工具类
* @author 奇男子
* @version 1.0
*/
public class MyArrays {
/**
* 数组的排序
* @param a 目标数组
*/
public static void sort(int[] a){
for (int i = 0; i < a.length-1; i++) {
for (int j = 0; j < a.length-1-i; j++) {
if(a[j] > a[j+1]){
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
}
/**
* 数组的查找,必须先排序,在查找
* @param a 目标数组
* @param key 需要查找的键
* @return 如果搜索的元素包含在数组中就返回元素的下标; 否则,返回(-插入点-1)
*/
public static int binarySearch(int[] a,int key){
int start = 0;
int end = a.length-1;
while(start <= end){
int mid = (start+end)/2;
if(key < a[mid]){
end = mid-1;
}else if(key > a[mid]){
start = mid+1;
}else{
return mid;
}
}
return -start-1;
}
/**
* 拷贝数组
* @param original 目标数组
* @param newLength 新数组的长度
* @return 新数组
*/
public static int[] copyOf(int[] original, int newLength){
int copyLength = original.length;
if(copyLength > newLength){
copyLength = newLength;
}
int[] newArr = new int[newLength];
for (int i = 0; i < copyLength; i++) {
newArr[i] = original[i];
}
return newArr;
}
/**
* 引用数据类型数组的扩容(不支持基本数据类型)
* @param original
* @param newLength
* @return
*/
public static <T> T[] copyOf(T[] original , int newLength){
int copyLength = original.length;
if(copyLength > newLength){
copyLength = newLength;
}
//获取元素的类型
Class<? extends Object[]> clazz = original.getClass();//String[].class
Class<?> componentType = clazz.getComponentType();//String.clss
//利用反射创建数组
@SuppressWarnings("unchecked")
T[] ts = (T[]) Array.newInstance(componentType, newLength);
//遍历源数组,将数据复制到新数组中
for (int i = 0; i < copyLength; i++) {
//获取源数组的数据
Object element = Array.get(original, i);
//赋值给新数组
Array.set(ts, i, element);
}
return ts;
}
/**
* 拷贝区间数组
* @param original 目标数组
* @param from 开始下标-包含
* @param to 结束下标 - 排他
* @return 新数组
*/
public static int[] copyOfRange(int[] original, int from, int to){
int newLength = to-from;
int[] newArr = new int[newLength];
int index = 0;
for (int i = from; i < to; i++) {
newArr[index++] = original[i];
}
return newArr;
}
/**
* 替换全部元素
* @param a 目标数组
* @param val 替换的值
*/
public static void fill(int[] a, int val){
fill(a, 0, a.length, val);
}
/**
* 替换区间元素
* @param a 目标数组
* @param fromIndex 开始下标 - 包含
* @param toIndex 结束下标 - 排他
* @param val 替换的值
*/
public static void fill(int[] a, int fromIndex, int toIndex, int val){
for (int i = fromIndex; i < toIndex; i++) {
a[i] = val;
}
}
/**
* 将数组转换为字符串
* @param a 目标数组
* @return 转换后的字符串
*/
public static String toString(int[] is) {
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int element : is) {
if(sb.length() != 1){
sb.append(",");
}
sb.append(element);
}
sb.append("]");
return sb.toString();
}
/**
* 将数组转换为字符串
* @param a 目标数组
* @return 转换后的字符串
*/
public static <T> String toString(T[] a){
StringBuffer sb = new StringBuffer();
sb.append("[");
for (int i = 0; i < Array.getLength(a); i++) {
if(sb.length() != 1){
sb.append(",");
}
Object element = Array.get(a, i);
sb.append(element);
}
sb.append("]");
return sb.toString();
}
}
2.业务与逻辑分离的思想
需求:
用户选择获取数据的方式(本地数据、网络数据)
实现
版本01
版本01:if-else直接实现
public class Test01 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请选择获取数据的方式:");
System.out.println("1-获取本地数据");
System.out.println("2-获取网络数据");
int num = scan.nextInt();
if(num == 1){
System.out.println("请填写需要拷贝文件的路径:");
String path = scan.next();
File file = new File(path);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(path));
bos = new BufferedOutputStream(new FileOutputStream(file.getName()));
byte[] bs = new byte[1024];
int len;
while((len=bis.read(bs)) != -1){
bos.write(bs, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}else if(num == 2){
//https://wx2.sinaimg.cn/mw690/e2438f6cly1hoo3qpm7vrj21111jk4mn.jpg
System.out.println("请填写下载图片的网址:");
String path = scan.next();
try {
//创建链接对象
URL url = new URL(path);
//获取连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置参数
connection.setConnectTimeout(5000);//设置连接超时时间
connection.setReadTimeout(5000);//设置读取数据超时时间
connection.setDoInput(true);//设置是否允许使用输入流
connection.setDoOutput(true);//设置是否允许使用输出流
//获取响应状态码
int code = connection.getResponseCode();
if(code == HttpURLConnection.HTTP_OK){
//文件名
String fileName = path.substring(path.lastIndexOf("/")+1);
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
byte[] bs = new byte[1024];
int len;
while((len = bis.read(bs)) != -1){
bos.write(bs, 0, len);
}
bis.close();
bos.close();
}else if(code == HttpURLConnection.HTTP_NOT_FOUND){
System.out.println("页面未找到");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
scan.close();
}
}
版本02
版本02:简单分离,优化if-else问题
优化:使用类、接口哪个更好?
注意:
如果就只是固定功能或者说DataSource仅是有抽象方法就用接口更好
如果需要添加新的功能用类更好
public class Test01 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请选择获取数据的方式:");
System.out.println("1-获取本地数据");
System.out.println("2-获取网络数据");
int num = scan.nextInt();
if(num == 1){
LocalDataSource dataSource = new LocalDataSource();
dataSource.getDataSource();
}else if(num == 2){
NetworkDataSource dataSource = new NetworkDataSource();
dataSource.getDataSource();
}
scan.close();
}
}
数据源
public abstract class DataSource {
public abstract void getDataSource();
}
//获取本地资源的类
public class LocalDataSource extends DataSource{
private Scanner scan;
public LocalDataSource() {
scan = new Scanner(System.in);
}
@Override
public void getDataSource() {
System.out.println("请填写需要拷贝文件的路径:");
String path = scan.next();
File file = new File(path);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(path));
bos = new BufferedOutputStream(new FileOutputStream(file.getName()));
byte[] bs = new byte[1024];
int len;
while((len=bis.read(bs)) != -1){
bos.write(bs, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//获取网络资源的类
public class NetworkDataSource extends DataSource{
private Scanner scan;
public NetworkDataSource() {
scan = new Scanner(System.in);
}
@Override
public void getDataSource() {
//https://wx2.sinaimg.cn/mw690/e2438f6cly1hoo3qpm7vrj21111jk4mn.jpg
System.out.println("请填写下载图片的网址:");
String path = scan.next();
try {
//创建链接对象
URL url = new URL(path);
//获取连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置参数
connection.setConnectTimeout(5000);//设置连接超时时间
connection.setReadTimeout(5000);//设置读取数据超时时间
connection.setDoInput(true);//设置是否允许使用输入流
connection.setDoOutput(true);//设置是否允许使用输出流
//获取响应状态码
int code = connection.getResponseCode();
if(code == HttpURLConnection.HTTP_OK){
//文件名
String fileName = path.substring(path.lastIndexOf("/")+1);
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
byte[] bs = new byte[1024];
int len;
while((len = bis.read(bs)) != -1){
bos.write(bs, 0, len);
}
bis.close();
bos.close();
}else if(code == HttpURLConnection.HTTP_NOT_FOUND){
System.out.println("页面未找到");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
版本03
版本03:在原有基础,新增功能
对菜单和数据源都在数据中心配合配置文件进行初始,可维护性更好
将菜单信息放在配置文件,再取出来存在一个集合里(ps:代码中的数据中心dataSource)
再打印查看展示
本地资源,网络资源路径放在配置文件
初始化数据源的循环获取对象,放在dataSource添加其他功能,即新增功能,更改配置文件
public class Test01 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
showMenu();
int num = scan.nextInt();
DataSource dataSource = getDataSourceObject(num);
dataSource.getDataSource();
scan.close();
}
public static void showMenu(){
System.out.println("请选择获取数据的方式:");
ArrayList<String> menulist = DataCenter.menuList;
for (String element : menulist) {
System.out.println(element);
}
}
public static DataSource getDataSourceObject(int num){
DataSource dataSource = DataCenter.dataSourceList.get(num-1);
return dataSource;
}
}
数据中心
//数据中心
public class DataCenter {
public static final ArrayList<String> menuList;
public static final ArrayList<DataSource> dataSourceList;
//初始化菜单数据
static{
menuList = new ArrayList<>();
Properties p = new Properties();
try {
p.load(DataCenter.class.getClassLoader().getResourceAsStream("menuConfig.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String data = p.getProperty("data");
String[] split = data.split(",");
Collections.addAll(menuList, split);
}
//初始化数据源数据
static{
dataSourceList = new ArrayList<>();
Properties p = new Properties();
try {
p.load(DataCenter.class.getClassLoader().getResourceAsStream("dataSourceConfig.properties"));
} catch (IOException e) {
e.printStackTrace();
}
String data = p.getProperty("data");
String[] split = data.split(",");
for (String classPath : split) {
try {
Class<?> clazz = Class.forName(classPath);
DataSource dataSouce = (DataSource) clazz.newInstance();
dataSourceList.add(dataSouce);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
配置文件
menuConfig.properties
注意:写进去不是中文显示为正常现象
data=1-\u83B7\u53D6\u672C\u5730\u6570\u636E,2-\u83B7\u53D6\u7F51\u7EDC\u6570\u636E,3-\u83B7\u53D6\u5176\u4ED6\u6570\u636E
dataSourceConfig.properties
data=com.qf.reflex02.LocalDataSource,com.qf.reflex02.NetworkDataSource,com.qf.reflex02.OtherDataSource
数据源
public abstract class DataSource {
public abstract void getDataSource();
}
//获取本地资源的类
public class LocalDataSource extends DataSource{
private Scanner scan;
public LocalDataSource() {
scan = new Scanner(System.in);
}
@Override
public void getDataSource() {
System.out.println("请填写需要拷贝文件的路径:");
String path = scan.next();
File file = new File(path);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(path));
bos = new BufferedOutputStream(new FileOutputStream(file.getName()));
byte[] bs = new byte[1024];
int len;
while((len=bis.read(bs)) != -1){
bos.write(bs, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
//获取网络资源的类
public class NetworkDataSource extends DataSource{
private Scanner scan;
public NetworkDataSource() {
scan = new Scanner(System.in);
}
@Override
public void getDataSource() {
//https://wx2.sinaimg.cn/mw690/e2438f6cly1hoo3qpm7vrj21111jk4mn.jpg
System.out.println("请填写下载图片的网址:");
String path = scan.next();
try {
//创建链接对象
URL url = new URL(path);
//获取连接对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置参数
connection.setConnectTimeout(5000);//设置连接超时时间
connection.setReadTimeout(5000);//设置读取数据超时时间
connection.setDoInput(true);//设置是否允许使用输入流
connection.setDoOutput(true);//设置是否允许使用输出流
//获取响应状态码
int code = connection.getResponseCode();
if(code == HttpURLConnection.HTTP_OK){
//文件名
String fileName = path.substring(path.lastIndexOf("/")+1);
BufferedInputStream bis = new BufferedInputStream(connection.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileName));
byte[] bs = new byte[1024];
int len;
while((len = bis.read(bs)) != -1){
bos.write(bs, 0, len);
}
bis.close();
bos.close();
}else if(code == HttpURLConnection.HTTP_NOT_FOUND){
System.out.println("页面未找到");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//新增功能的类
public class OtherDataSource extends DataSource{
@Override
public void getDataSource() {
System.out.println("获取其他数据");
}
}
3.操作注解
简单涉及注解开发,没有遵循注解规范就报错,当然这里处理是随便抛的异常
注意:这里为前面反射获取注解信息及实际运用做了补充
工具类里,利用反射,设置权限,获取注解,属性的数据拿到
数据字符串拼接用StringBuilder或者Strinngbuffer
//表
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface TableInfo {
String name();
}
//属性
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldInfo {
String name();
String type();
}
学生类
添加注解
package com.qf.reflex03;
@TableInfo(name="s_student")
public class Student {
@FieldInfo(name="s_name",type="varchar")
private String name;
@FieldInfo(name="s_sex",type="varchar")
private String sex;
@FieldInfo(name="s_age",type="int")
private int age;
public Student() {
}
public Student(String name, String sex, int age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
}
工具类
public class DBUtil {
public static String generateInsertSQL(Object obj){
Class<? extends Object> clazz = obj.getClass();
//获取表名
TableInfo tableInfo = clazz.getAnnotation(TableInfo.class);
if(tableInfo == null){
throw new RuntimeException();
}
String tableName = tableInfo.name();
StringBuffer names = new StringBuffer();
StringBuffer values = new StringBuffer();
//获取属性数据
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
FieldInfo fieldInfo = field.getAnnotation(FieldInfo.class);
String name = fieldInfo.name();
String type = fieldInfo.type();
if(names.length() != 0){
names.append(",");
}
names.append(name);
try {
if(values.length() != 0){
values.append(",");
}
Object fieldData = field.get(obj);
if(type.equals("varchar")){
values.append("'");
}
values.append(fieldData);
if(type.equals("varchar")){
values.append("'");
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
String sql = "INSERT INTO " + tableName + "(" + names.toString() + ") VALUES(" + values.toString() + ");";
return sql;
}
}
测试类
public class Test01 {
public static void main(String[] args) {
Student stu = new Student("奇男子", "男", 18);
String sql = DBUtil.generateInsertSQL(stu);
System.out.println(sql);
//INSERT INTO s_student(s_name,s_sex,s_age) VALUES('奇男子','男',18);
}
}
总结
1.反射案例 – 万能数组扩展
注意:
1.泛型的使用2.反射案例 – 业务与逻辑分离的思想
注意:
1.理解思想
2.灵活使用配置文件
3.理解数据中心DataCenter3.反射案例 – 操作注解
注意:
1.理解注解是可以给类、属性、方法提供额外信息