Method对象可以得到任何一个类的任何方法的定义(只需要传入方法的名字和参数即可)
class Ming {
private void speak() {
System.out.println("ff");
}
}
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Method method = Ming.class.getDeclaredMethod("speak");
System.out.println(method.toString());
}
}
View Code
有参数的话,需要int.class
class Ming {
void speak(int a) {
System.out.println("ff");
}
}
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Ming s = new Ming();
Method method = s.getClass().getDeclaredMethod("speak", int.class);
System.out.println(method);
}
}
View Code
输出 private void Ming.speak()
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
得到类的构造函数
getConstructor只能得到public的
import java.lang.reflect.Constructor;
class Second {
int a, b;
public Second() {
a = b = 1;
}
Second(int _a, int _b) {
a = _a;
b = _b;
}
void show() {
System.out.println(a + b);
}
};
public class Main {
public static void main(String[] args) throws InterruptedException, NoSuchMethodException, SecurityException {
Second second = new Second();
System.out.println(second.toString());
System.out.println(second.getClass().getConstructor().toString());
// getConstructor只能用在public 的构造方法
/* 输出
Second@7852e922
public Second()
*/
}
}
View Code
getDeclaredConstructor可以得到所有的
import java.lang.reflect.Constructor;
class Second {
int a, b;
public Second() {
a = b = 1;
}
Second(int _a, int _b) {
a = _a;
b = _b;
}
void show() {
System.out.println(a + b);
}
};
public class Main {
public static void main(String[] args) throws InterruptedException, NoSuchMethodException, SecurityException {
Second second = new Second();
System.out.println(second.toString());
System.out.println(second.getClass().getDeclaredConstructor(int.class, int.class).toString());
// getConstructor只能用在public 的构造方法
/* 输出
Second@7852e922
Second(int,int)
*/
}
}
View Code
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
getField得到的是变量名
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Ming {
private void speak() {
System.out.println("ff");
}
public int vb;
public int a;
public Ming() {}
}
public class Main {
public static void main(String[] args) throws NoSuchMethodException {
Ming ming = new Ming();
Field[] fields = ming.getClass().getFields();
for (Field field : fields) {
System.out.println(field.toString());
}
//public int Ming.vb
//public int Ming.a
}
}
View Code
可以得到单个的,传入名字就可以
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Ming {
private void speak() {
System.out.println("ff");
}
private int vb;
public int a;
public Ming() {}
}
public class Main {
public static void main(String[] args) throws Exception {
Ming ming = new Ming();
Field field = ming.getClass().getDeclaredField("vb");
System.out.println(field.toString());
}
}
View Code
抛出异常,绝招,直接throw Expection即可,不用throw XXXExpection
反射机制,大概就是得到名字,就可以得到所有东西,可以修改属性。
得到一个类的名字,可以用forname方法生成他的一个对象。
然后,可以用getField得到它的一个属性,也就是变量。
然后用Field.set(对象名, val)就可以修改成功。也可以修改private的变量。超劲。
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.Scanner;
class Ming {
private int a;
Ming() {
}
void speak() {
System.out.println("fff");
}
int show() {
return a;
}
}
public class Main {
public static void main(String[] args) throws Exception { // 666
Class clazz = Class.forName("Ming");
Ming s = (Ming)clazz.newInstance();
Field field = clazz.getDeclaredField("a");
field.setAccessible(true); //修改private
field.set(s, 20);
System.out.println(s.show());
}
}
View Code
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.Scanner;
class Ming {
private int a;
Ming() {
}
void speak() {
System.out.println("fff");
}
int show() {
return a;
}
}
public class Main {
public static void main(String[] args) throws Exception { // 666
Class clazz = Class.forName(Ming.class.getName()); //这样来
Ming s = (Ming)clazz.newInstance();
Field field = clazz.getDeclaredField("a");
field.setAccessible(true); //修改private
field.set(s, 20);
System.out.println(s.show());
}
}
View Code
利用java反射得到一个类的所有东西,不能得到方法实现的内容
import java.io.File;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Scanner;
class Person {
private String name, sex, idNo;
Integer age;
Boolean isMerried;
int a;
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public String getIdNo() {
return idNo;
}
public Integer getAge() {
return age;
}
public Boolean getIsMerried() {
return isMerried;
}
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public void setAge(Integer age) {
this.age = age;
}
public void setIsMerried(Boolean isMerried) {
this.isMerried = isMerried;
}
private void show(int a, int b, char c, int d) {
}
public Person() {
}
public Person(String idNo) {
this.idNo = idNo;
}
public Person(String idNo, Integer fuck) {
}
public String toString() {
return name + " " + sex + " " + age + " " + idNo + " " + isMerried; // 需要两个空格?,因为中文,靠
}
}
class PersonProxy {
private Person T;
private final String OUTPUT = "output.txt";
private PrintWriter output = new PrintWriter(OUTPUT);
PersonProxy(Person T) {
this.T = T;
}
private void writeFile(String message) {
}
}
public class Main {
static private final String INPUT = "input.txt";
static private final String OUTPUT = "output.txt";
static private final String CMP = "java.lang.";
static private final int MAXN = 200;
static private int[] del = new int[MAXN];
static private int DFN = 0;
private static String getString(String str, String className) {
++DFN;
for (int j = 0; j < str.length(); ++j) {
if (del[j] == DFN)
continue;
String t = "";
if (j + 10 < str.length()) {
t = str.substring(j, j + 10);
if (t.compareTo(CMP) == 0) {
for (int k = j; k < j + 10; ++k)
del[k] = DFN;
}
}
if (j + className.length() + 1 < str.toString().length()) {
t = str.substring(j, j + className.length() + 1);
if (t.compareTo(className + ".") == 0) {
for (int k = j; k < j + className.length() + 1; ++k)
del[k] = DFN;
}
}
}
String out = "\t";
for (int j = 0; j < str.length(); ++j) {
if (del[j] == DFN)
continue;
out += str.charAt(j);
}
return out + ";";
}
private static void showClassInformation(String className) throws Exception {
System.out.println("class" + " " + className + " {");
Class clazz = Class.forName(className);
Field[] fs = clazz.getDeclaredFields();
for (Field i : fs) {
System.out.println(getString(i.toString(), className));
}
Constructor[] cs = clazz.getDeclaredConstructors();
for (Constructor i : cs) {
System.out.println(getString(i.toString(), className));
}
Method[] ms = clazz.getDeclaredMethods();
for (Method i : ms) {
System.out.println(getString(i.toString(), className));
}
System.out.println("}");
}
public static void getInstance(String className) throws Exception {
Class clazz = Class.forName(className);
Person ps = (Person) clazz.newInstance();
ps.setIdNo("5122245566");
ps.setName("张小平");
ps.setAge(23);
ps.setSex("Male");
ps.setIsMerried(true);
PrintWriter output = new PrintWriter(OUTPUT);
output.println("idNo=" + ps.getIdNo());
output.println("name=" + ps.getName());
output.println("age=" + ps.getAge());
output.println("sex=" + ps.getSex());
output.println("isMerried=" + ps.getIsMerried());
output.close();
}
public static void getFile(String className) throws Exception {
Class clazz = Class.forName(className);
Person ps = (Person) clazz.newInstance();
Scanner input = new Scanner(new File(INPUT));
String str;
str = input.next();
ps.setIdNo(str.substring(str.lastIndexOf('=') + 1, str.length()));
str = input.next();
ps.setName(str.substring(str.lastIndexOf('=') + 1, str.length()));
str = input.next();
ps.setAge(Integer.parseInt(str.substring(str.lastIndexOf('=') + 1, str.length())));
str = input.next();
ps.setSex(str.substring(str.lastIndexOf('=') + 1, str.length()));
str = input.next();
ps.setIsMerried(Boolean.parseBoolean(str.substring(str.lastIndexOf('=') + 1, str.length())));
System.out.println(ps.toString());
input.close();
}
public static void main(String[] args) throws Exception {
showClassInformation("Person");
getInstance("Person");
getFile("Person");
}
}
View Code
文件追加操作
public void writeFile(String methodName, String parm) throws IOException {
output = new PrintWriter(new FileWriter(new File(OUTPUT), true)); // 文件追加
String message = "时间: " + getNowTime() + " 方法名称: " + methodName + " 参数" + parm;
output.println(message);
output.close();
}
利用动态代理,需要的是设计一个接口,里面写了什么,就能代理出来。
public interface Speakable {
public void speak(String message);
public String getName();
public String getSex();
public String getIdNo();
public Integer getAge();
public Boolean getIsMerried();
public void setName(String name);
public void setSex(String sex);
public void setIdNo(String idNo);
public void setAge(Integer age);
public void setIsMerried(Boolean isMerried);
}
写一个这样的接口,必须只能是接口
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyProxy implements InvocationHandler {
private Object proxied;
MyProxy(Object proxied) {
this.proxied = proxied;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
method.invoke(this.proxied, args);
System.out.println(PersonProxy.getNowTime()); //这一条就是
return null;
}
}
加上一条语句,就是每执行接口中的一个方法的时候,下面那句语句就能执行。所以就不需要在类中为每一个方法都写一句一毛一样的
new Person();
Speakable speakable = (Speakable)Proxy.newProxyInstance(Speakable.class.getClassLoader(), new Class[] {Speakable.class}, new MyProxy(person));
speakable.setAge(2); //会输出时间
System.out.println(person.getAge()); //不会输出时间
然后这样,每调用接口的一个方法,都会输出当前的时间。
这样做的好处就是,把一个对象,弄了一个代理给他,这样,那个代理做的东西,会直接影响那个对象的值,并且能够多输出一些你想要的东西。
Map的使用方法(假)
需要注意要判断后才能使用
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.omg.PortableInterceptor.INACTIVE;
class Student {
private String idNo, name;
private int score;
public Student(String idNo, String name, int score) {
super();
this.idNo = idNo;
this.name = name;
this.score = score;
}
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
class Score {
private String course;
private int score;
public Score(String course, int score) {
super();
this.course = course;
this.score = score;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Student> st = new ArrayList<Student>();
ArrayList<Score> sc = new ArrayList<Score>();
Map<String, Integer> sumOfStudentScore = new HashMap<String, Integer>();
Map<String, Integer> numberOfStudentSelect = new HashMap<String, Integer>();
Map<String, Integer> mx = new HashMap<String, Integer>();
Map<String, Integer> mi = new HashMap<String, Integer>();
while (true) {
System.out.println("请输入学生的学号、姓名、选修课程、课程成绩(学号是小数点结束输入)");
String idNo = input.next();
if (idNo.compareTo(".") == 0) break;
String studentName = input.next();
String courseName = input.next();
int courseScore = input.nextInt();
st.add(new Student(idNo, studentName, courseScore));
sc.add(new Score(courseName, courseScore));
}
for (int i = 0; i < sc.size(); ++i) {
String t = sc.get(i).getCourse();
int val = sc.get(i).getScore();
if (sumOfStudentScore.containsKey(t)) {
int res = sumOfStudentScore.get(t) + val;
sumOfStudentScore.put(t, res);
res = numberOfStudentSelect.get(t) + 1;
numberOfStudentSelect.put(t, res);
res = mx.get(t); // 需要判断了才能使用
mx.put(t, Math.max(res, val));
res = mi.get(t);
mi.put(t, Math.min(res, val));
} else {
sumOfStudentScore.put(t, val);
numberOfStudentSelect.put(t, 1);
mx.put(t, val);
mi.put(t, val);
}
}
// System.out.println("fff");
// for (String s : sumOfStudentScore.keySet()) {
// System.out.println(s + " " + sumOfStudentScore.get(s));
// }
for (String s : sumOfStudentScore.keySet()) {
System.out.println("课程: " + s + " 平均分是:" + sumOfStudentScore.get(s) * 1.0 / numberOfStudentSelect.get(s));
System.out.println("其中最高分是:" + mx.get(s) + " " + "最低分是:" + mi.get(s));
}
String idNo;
System.out.println("请输入想要查询的学生成绩的id");
idNo = input.next();
for (int i = 0; i < st.size(); ++i) {
if (st.get(i).getIdNo().compareTo(idNo) == 0) {
System.out.println(st.get(i).getScore());
}
}
}
}
View Code
泛型的使用方法
public class Main {
public static void main(String[] args) {
PersonManager<Student> ps = new PersonManager<Student>();
ps.add(new Student("2015", "liuweiming"));
ps.add(new Student("2014", "liuhaha"));
ps.findAll();
}
}
public class Person {
String idNo, name;
}
import java.util.*;
public class PersonManager<T extends Person> {
List<T> list;
public PersonManager () {
// TODO Auto-generated method stub
// System.out.println("fff");
list = new ArrayList<T>();
}
// public PersonManager<T> () {
//
// }
public boolean add(T t) {
if (list.contains(t)) return false;
list.add(t);
return true;
}
public boolean remove(T t) {
if (!list.contains(t)) return false;
list.remove(t);
return true;
}
public T findById(int id) {
for (T i : list) {
if (i.getClass().isInstance(Student.class)) {
if (((Student)i).getIdNo().compareTo("" + id) == 0) {
return i;
}
} else {
if (((Teacher)i).getIdNo().compareTo("" + id) == 0) {
return i;
}
}
}
return list.get(0); // wrong answer,
}
public void findAll() {
for (T i : list) {
System.out.println(i.toString());
}
}
}
public class Student extends Person {
String idNo, name;
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Student(String idNo, String name) {
super();
this.idNo = idNo;
this.name = name;
}
@Override
public String toString() {
return idNo + " " + name;
}
}
public class Teacher extends Person {
String idNo, name;
public String getIdNo() {
return idNo;
}
public void setIdNo(String idNo) {
this.idNo = idNo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Teacher(String idNo, String name) {
super();
this.idNo = idNo;
this.name = name;
}
@Override
public String toString() {
return idNo + " " + name;
}
}
View Code
2017年12月28日 20:30:05
坑:
如果一个方法里面有了 throws了东西,那么调用这个方法的时候就要try catch,或者在调用这个方法中的那个方法里面也throws东西。
还有,要注意左边红色的错误啊。。。。
java的web,服务器开了888端口,然后客户端要访问的也就是888端口。localhost就是127.0.0.1,不能写其他地址。写其他地址相当于访问别人的电脑了。
那个getport,随机化的,不能setport啊。 socket.getPort()
package liuweiming;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.*;
import javax.sound.sampled.Port;
class SocketHandler implements Runnable {
private Socket socket;
public SocketHandler(Socket socket) {
this.socket = socket;
// TODO Auto-generated constructor stub
}
public void run() {
try {
InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String name = socket.getInetAddress().toString();
name += ":";
name += socket.getPort();
System.out.println(name + " Say: " + bufferedReader.readLine());
bufferedReader.close();
inputStreamReader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
public ServerThread() {
}
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(888);
while (true) {
Socket socket = serverSocket.accept(); // 等待接受
Thread thread = new Thread(new SocketHandler(socket));
thread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class Client {
String inetAddress;
int port;
String fuck;
public Client(String inetAddress, int port, String fuck) {
this.inetAddress = inetAddress;
this.port = port;
this.fuck = fuck;
}
public void did() {
Socket socket;
try {
socket = new Socket(inetAddress, port);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
printWriter.write(fuck);
printWriter.flush();
printWriter.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
Thread serverThread = new Thread(new ServerThread()); // 开启服务
serverThread.start();
Client client = new Client("127.0.0.1", 888, "df");
client.did();
Client client2 = new Client("127.0.0.1", 888, "fff");
client2.did();
}
}
View Code
这次直接用浏览器做客户端,注意要加上一些话语才能show到去网页上。还有不知为何输出了两次(本地)
感觉访问了两次一样因为那个socket.getPort()不同的。
package liuweiming;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.*;
import javax.sound.sampled.Port;
class Sever {
public void work() {
try {
ServerSocket serverSocket = new ServerSocket(8888); //监听这个端口
while (true) { //一直accept
Socket socket = serverSocket.accept();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String string = bufferedReader.readLine();
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
System.out.println(socket.getInetAddress().toString() + " " + socket.getPort() + " " + string);
/*MK*/
printWriter.println("HTTP/1.1 200 OK");
printWriter.println("Content-Type: text/html;charset=UTF-8");
printWriter.println();
/*Mk*/
printWriter.println("<p> fff </p>");
printWriter.flush();
bufferedReader.close();
printWriter.close();
socket.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
Sever sever = new Sever();
sever.work();
}
}
View Code
算法复杂度分析,大O阶、小O,Ω、.....
2018年1月3日 22:03:03
如果TomCat不能用
就在那个setclasspath.bat上,
加上那两个即可
如果想看看那个startup.bat为什么不行,可以在最后,也就是end;后面加上PAUSE让它停止。