1.創(chuàng)建Person類,Person的屬性有: String name 姓名 String sex 性別 Integer age 年齡, String idNo 身份證號(hào) Boolean isMarried 是否已婚 請生成相應(yīng)的getter、setter方法。請編寫注解@Label,表示所注解對象的中文名稱, 請把@Label注解標(biāo)注在Person類和Person的每個(gè)屬性上面。 請編寫PersonInput類,負(fù)責(zé)提示錄入人員的相關(guān)屬性,提示必須是注解@Label所標(biāo)注的中文名稱。 請編寫PersonDisplay,負(fù)責(zé)顯示人員信息,顯示時(shí)的屬性名稱必須為注解@Label所標(biāo)注的中文名稱 PersonInput類與PersonDisplay類實(shí)現(xiàn)了共同的接口PersonAction,接口PersonAction有方法process,方法process的簽名為:public Person process(Person person);
2.
在第一題目的基礎(chǔ)上,編寫注解@Column, 屬性有Label 表示類的屬性的顯示名稱, Nullable 表示是否允許屬性值為空, MaxLength 表示文本屬性的最大長度, MinLength表示文本屬性的最小長度, MaxValue表示最大值, MinValue表示最小值,
把注解@Column加在Person類的每個(gè)屬性上,在輸入Person時(shí)根據(jù)注解@Column的配置進(jìn)行校驗(yàn)。 第一題的@Label只標(biāo)注在類上。根據(jù)注解生成Person類對應(yīng)的數(shù)據(jù)庫表創(chuàng)建語句,以及生成數(shù)據(jù)庫表的刪除、新增、修改SQL語句。 并利用JDBC,實(shí)現(xiàn)數(shù)據(jù)庫操作。
第一題:
@Label注解:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Label {
String value();
}
person類:
public class Person {
@Label("姓名")
String name; //姓名
@Label("性別")
String sex; //性別
@Label("年齡")
Integer age; //年齡
@Label("身份證號(hào)")
String idNo; //身份證號(hào)
@Label("是否已婚")
Boolean isMarried; //是否已婚
public Person() {
}
public Person(String name, String sex, Integer age, String idNo, boolean isMarried) {
this.name = name;
this.sex = sex;
this.age = age;
this.idNo = idNo;
this.isMarried = isMarried;
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public Boolean isMarried() {
return isMarried;
}
public void setMarried(Boolean married) {
isMarried = married;
}
}
?PersonAction接口:
//注解處理器接口
public interface PersonAction {
public Person process(Person person) throws IllegalAccessException;
}
PersonInput類,負(fù)責(zé)提示錄入人員的相關(guān)屬性,提示必須是注解@Label所標(biāo)注的中文名稱。
import java.lang.reflect.Field;
import java.util.Scanner;
/**
* 負(fù)責(zé)提示錄入人員的相關(guān)屬性,提示必須是注解@Label所標(biāo)注的中文名稱。
*/
public class PersonInput implements PersonAction {
@Override
public Person process(Person person) throws IllegalAccessException {
Scanner input = new Scanner(System.in);
Class clazz = person.getClass();//獲取Class對象
Field[] fields = clazz.getDeclaredFields();//通過Class對象獲取Field對象
//遍歷獲取的person對象的所有字段
for (Field field : fields) {
Object obj = field.get(person);
if (obj == null) {
String s = field.getAnnotation(Label.class).value();
System.out.print("請輸入" + s + ":");
String s1 = input.next();
if (field.getType().getName().contains("String")) {//獲取的字段是String類型
field.set(person, s1);
} else if (field.getType().getName().contains("Integer")) {//獲取的字段是Integer類型
field.set(person, Integer.parseInt(s1));
} else if (field.getType().getName().contains("Boolean")) {//獲取字段是Boolean類型
field.set(person, Boolean.parseBoolean(s1));
}
}
}
return person;
}
}
PersonDisplay,負(fù)責(zé)顯示人員信息,顯示時(shí)的屬性名稱必須為注解@Label所標(biāo)注的中文名稱
import java.lang.reflect.Field;
/**
* 負(fù)責(zé)顯示人員信息,顯示時(shí)的屬性名稱必須為注解@Label所標(biāo)注的中文名稱,
*/
public class PersonDisplay implements PersonAction {
@Override
public Person process(Person person) throws IllegalAccessException {
Class clazz = person.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
//獲取Label注解的value值
if (field.isAnnotationPresent(Label.class)) {
String name = field.getAnnotation(Label.class).value();
System.out.print(name + ":");
}
//獲取屬性的值
Object obj = field.get(person);
System.out.println(obj);
}
return person;
}
}
測試類:
public class text {
public static void main(String[] args) throws IllegalAccessException {
Person person = new Person();
PersonInput personInput = new PersonInput();
personInput.process(person);
PersonDisplay personDisplay = new PersonDisplay();
personDisplay.process(person);
}
}
運(yùn)行結(jié)果:
?第二題:
@Column注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.FIELD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Column {
Label label(); // 表示類的屬性的顯示名稱,
boolean Nullable() default false;// Nullable 表示是否允許屬性值為空
int MaxLength() default 100;// MaxLength 表示文本屬性的最大長度
int MinLength() default 0;// MinLength表示文本屬性的最小長度
int MaxValue() default 999999999;// MaxValue表示最大值
int MinValue() default 0;// MinValue表示最小值
}
Person類:
@Column(label = @Label("Person"))
public class Person {
@Column(label = @Label("姓名"))
String name; //姓名
@Column(label = @Label("性別"))
String sex; //性別
@Column(label = @Label("年齡"), MaxValue = 120)
Integer age; //年齡
@Column(label = @Label("身份證號(hào)"))
String idNo; //身份證號(hào)
@Column(label = @Label("是否已婚"))
Boolean isMarried; //是否已婚
public Person() {
}
public Person(String name, String sex, Integer age, String idNo, boolean isMarried) {
this.name = name;
this.sex = sex;
this.age = age;
this.idNo = idNo;
this.isMarried = isMarried;
}
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public Boolean isMarried() {
return isMarried;
}
public void setMarried(Boolean married) {
isMarried = married;
}
}
MySqlDAO類:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class MySqlDAO {
public static Connection getConnection() throws Exception {
String driverName = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/demo";
String userName = "root";
String pw = "xx";
Class.forName(driverName);
Connection con = DriverManager.getConnection(url, userName, password);
return con;
}
public static PreparedStatement preparedStatement(String sql) throws Exception {
return getConnection().prepareStatement(sql);
}
}
CreateSQL類:
import java.lang.reflect.Field;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
/**
* 把注解@Column加在Person類的每個(gè)屬性上,在輸入Person時(shí)根據(jù)注解@Column的配置進(jìn)行校驗(yàn)。
* 第一題的@Label只標(biāo)注在類上。根據(jù)注解生成Person類對應(yīng)的數(shù)據(jù)庫表創(chuàng)建語句,以及生成數(shù)據(jù)庫表的刪除、新增、修改SQL語句。
* 并利用JDBC,實(shí)現(xiàn)數(shù)據(jù)庫操作。
*/
public class CreateSQL {
static PreparedStatement pd = null;
static ResultSet rs;
static Scanner input = new Scanner(System.in);
public String CreateTable(Person person) {
Class<? extends Person> clazz = person.getClass();
Field[] fields = clazz.getDeclaredFields();
Label name = clazz.getAnnotation(Column.class).label();
StringBuilder sql = new StringBuilder("create table if not exists " + name.value() + "(\n");
for (Field field : fields) {
String str = field.getAnnotation(Column.class).label().value();
int maxLength = field.getAnnotation(Column.class).MaxLength();
//如果時(shí)Integer類型
if (field.getType().getName().contains("Integer")) {
sql.append(str).append(" int,\n");
}
//如果是Boolean或者String類型
if (field.getType().getName().contains("String") || field.getType().getName().contains("Boolean")) {
sql.append(str).append(" varchar(").append(maxLength).append("),\n");
}
//添加主鍵
if (str.equals("身份證號(hào)")) {
sql = new StringBuilder(sql.substring(0, sql.length() - 2));//截取字符串
sql.append(" primary key,\n");
}
}
sql = new StringBuilder(sql.substring(0, sql.length() - 2));
sql.append("\n);");
System.out.println(sql);
return sql.toString();
}
public String InsertInf(Person person) {
Class<? extends Person> clazz = person.getClass();
Label name = clazz.getAnnotation(Column.class).label();
StringBuilder sql = new StringBuilder("insert into " + name.value() + " values(");
Field[] fields = clazz.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
String value = field.getAnnotation(Column.class).label().value();
System.out.println("請輸入" + value + ": ");
String str = input.next();
//根據(jù)注解@Column的配置進(jìn)行校驗(yàn)
if (!isTrue(field, str)) {
i--;
continue;
}
//判斷性別輸入是否輸入正確
if (value.equals("性別")) {
if (!str.equals("男") && !str.equals("女")) {
System.out.println("您輸入的性別不符合規(guī)范請重新輸入!");
i--;
continue;
}
}
//判斷是否結(jié)婚輸入是否正確
if (value.equals("是否結(jié)婚")) {
if (!str.equals("是") && !str.equals("否")) {
System.out.println("您輸入的結(jié)婚情況不符合規(guī)范請重新輸入!");
i--;
continue;
}
}
if (!isContainNum(str)) {
sql.append("'").append(str).append("'").append(", ");
} else {
sql.append(str).append(", ");
}
}
sql = new StringBuilder(sql.substring(0, sql.length() - 2));
sql.append(");");
System.out.println(sql);
return sql.toString();
}
public String deleteInf(Person person) {
Class<? extends Person> clazz = person.getClass();
Label name = clazz.getAnnotation(Column.class).label();
StringBuilder sql = new StringBuilder("delete from " + name.value() + " where ");
Field[] fields = clazz.getDeclaredFields();
String value = fields[0].getAnnotation(Column.class).label().value();
System.out.println("請輸入您要?jiǎng)h除的" + value + ": ");
String str = input.next();
if (!isContainNum(str)) {
sql.append(value).append(" = ").append("'").append(str).append("'");
} else
sql.append(value).append(" = ").append(str).append(";");
System.out.println(sql);
return sql.toString();
}
//更新操作
public String updateInf(Person person) {
Class<? extends Person> clazz = person.getClass();
Label tableName = clazz.getAnnotation(Column.class).label();
String sql = "update " + tableName.value() + " set ";
Field[] fields = clazz.getDeclaredFields();
String[] values = new String[fields.length];
System.out.println("請輸入要修改的姓名:");
String str2 = input.nextLine();
System.out.println("請選擇您要修改的屬性:");
for (int i = 0; i < values.length; i++) {
values[i] = fields[i].getAnnotation(Column.class).label().value();
System.out.println((i + 1) + "--" + values[i]);
}
String choice = input.nextLine();
int choiceNum = Integer.parseInt(choice);
String str1;
while (true) {
System.out.println("請輸入修改后的值:");
str1 = input.nextLine();
if (isTrue(fields[choiceNum - 1], str1)) {
break;
}
}
switch (choiceNum) {
case 1:
if (!isContainNum(str1)) {
sql += values[0] + " = " + "\"" + str1 + "\"";
} else {
sql += values[0] + " = " + str1;
}
break;
case 2:
if (!isContainNum(str1)) {
sql += values[1] + " = " + "\"" + str1 + "\"";
} else {
sql += values[1] + " = " + str1;
}
break;
case 3:
if (!isContainNum(str1)) {
sql += values[2] + " = " + "\"" + str1 + "\"";
} else {
sql += values[2] + " = " + str1;
}
break;
case 4:
if (!isContainNum(str1)) {
sql += values[3] + " = " + "\"" + str1 + "\"";
} else {
sql += values[3] + " = " + str1;
}
break;
case 5:
if (!isContainNum(str1)) {
sql += values[4] + " = " + "\"" + str1 + "\"";
} else {
sql += values[4] + " = " + str1;
}
break;
default:
break;
}
if (!isContainNum(str2)) {
sql += " where " + fields[0].getAnnotation(Column.class).label() + " = " + "\"" + str2 + "\"";
} else {
sql += " where " + fields[0].getAnnotation(Column.class).label() + " = " + str2;
}
System.out.println(sql);
return sql;
}
//根據(jù)注解@Column的配置進(jìn)行校驗(yàn)
public boolean isTrue(Field f, String str) {
String value = f.getAnnotation(Column.class).label().value();
boolean nullable = f.getAnnotation(Column.class).Nullable();
int maxLength = f.getAnnotation(Column.class).MaxLength();
int minLength = f.getAnnotation(Column.class).MinLength();
int maxValue = f.getAnnotation(Column.class).MaxValue();
int minValue = f.getAnnotation(Column.class).MinValue();
if (!nullable && str.isEmpty()) {
System.out.println("輸入的信息不能為空!請重新輸入");
return false;
}
if (maxLength == 0) {
int num;
try {
num = Integer.parseInt(str);
} catch (Exception e) {
System.out.println("您輸入的" + value + "不符合規(guī)范!請重新輸入");
return false;
}
if (num < minValue || num > maxValue) {
System.out.println("您輸入的" + value + "不符合規(guī)范!請重新輸入");
return false;
}
} else {
int len = str.length();
if (len > maxLength || len < minLength) {
System.out.println("您輸入的" + value + "不符合規(guī)范!請重新輸入");
return false;
}
}
return true;
}
public static boolean isContainNum(String str) {
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) > '0' && str.charAt(i) < '9') {
return true;
}
}
return false;
}
}
ExecuteSQL類:
import java.sql.PreparedStatement;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.Scanner;
/**
* 把注解@Column加在Person類的每個(gè)屬性上,在輸入Person時(shí)根據(jù)注解@Column的配置進(jìn)行校驗(yàn)。
* 第一題的@Label只標(biāo)注在類上。根據(jù)注解生成Person類對應(yīng)的數(shù)據(jù)庫表創(chuàng)建語句,以及生成數(shù)據(jù)庫表的刪除、新增、修改SQL語句。
* 并利用JDBC,實(shí)現(xiàn)數(shù)據(jù)庫操作。
*/
public class ExecuteSQL {
static PreparedStatement ps = null;
static CreateSQL sql = new CreateSQL();
static Scanner input = new Scanner(System.in);
static Person person = new Person();
public static void main(String[] args) throws Exception {
mainMenu();
closeConnection();
}
public static void mainMenu() throws Exception {
System.out.println("請選擇您要進(jìn)行的操作:");
System.out.println("1--自動(dòng)生成表Person");
System.out.println("2--增加數(shù)據(jù)");
System.out.println("3--刪除數(shù)據(jù)");
System.out.println("4--修改數(shù)據(jù)");
System.out.println("5--退出程序");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
switch (choice) {
case 1:
createTable();
mainMenu();
break;
case 2:
insert();
mainMenu();
break;
case 3:
delete();
mainMenu();
break;
case 4:
update();
mainMenu();
break;
case 5:
break;
default:
System.out.println("請輸入正確的選項(xiàng)!");
mainMenu();
break;
}
}
//建表
public static void createTable() throws Exception {
System.out.println("生成表中......");
String create = sql.CreateTable(person);
ps = MySqlDAO.preparedStatement(create);
ps.executeUpdate();
System.out.println("成功生成");
}
//向表中添加信息
public static void insert() throws Exception {
try {
String insertSQL = sql.InsertInf(person);
ps = MySqlDAO.preparedStatement(insertSQL);
ps.executeUpdate();
} catch (SQLIntegrityConstraintViolationException e) {
System.out.println("您輸入的身份證號(hào)碼有重復(fù),請重新輸入");
insert();
}
}
//刪除信息1
public static void delete() throws Exception {
String deleteSQL = sql.deleteInf(person);
ps = MySqlDAO.preparedStatement(deleteSQL);
ps.executeUpdate();
}
//更新信息
public static void update() throws Exception {
String updateSQL = sql.updateInf(person);
ps = MySqlDAO.preparedStatement(updateSQL);
ps.executeUpdate();
}
public static void closeConnection() throws Exception {
ps.close();
MySqlDAO.getConnection().close();
}
}
運(yùn)行結(jié)果:(當(dāng)時(shí)時(shí)間不太夠,如果時(shí)間夠建議自己做一個(gè)GUI)
文章來源:http://www.zghlxwxcb.cn/news/detail-469012.html
?文章來源地址http://www.zghlxwxcb.cn/news/detail-469012.html
到了這里,關(guān)于【Java高級(jí)程序設(shè)計(jì)】注解實(shí)驗(yàn)的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!