1、非泛型类、无泛型方法
输出java.lang.Double类所有方法、属性
package com.lf.java.basic.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Scanner;
public class ReflectionTest {
public static void main(String[] args) throws ClassNotFoundException {
String name;
if (args.length > 0) {
name = args[0];
}
Scanner in = new Scanner(System.in);
System.out.println("Enter class name (e.g. java.util.Date): ");
name = in.next();
try { // print class name and superclass name (if != Object)
Class cl = Class.forName(name);
Class supercl = cl.getSuperclass();
Class[] interfaces = cl.getInterfaces();
String modifiers = Modifier.toString(cl.getModifiers());
if (modifiers.length() > 0) {
System.out.print(modifiers + " ");
}
System.out.print("class " + name);
if (supercl != null && supercl != Object.class) {
System.out.print(" extends " + supercl.getName());
}
if (interfaces.length > 0) {
System.out.print(" implements ");
}
for (int i = 0; i < interfaces.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(interfaces[i].getName());
}
System.out.print("\n{\n");
printConstructors(cl);
System.out.println();
printMethods(cl);
System.out.println();
printFields(cl);
System.out.println("}");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.exit(0);
}
public static void printConstructors(Class cl) {
{
Constructor[] constructors = cl.getDeclaredConstructors();
for (Constructor c : constructors) {
// 获取当前属性获得的对象
// Class declaringClass = c.getDeclaringClass();
// System.out.println(declaringClass.getName());
String name = c.getName();
System.out.print(" ");
String modifiers = Modifier.toString(c.getModifiers());
if (modifiers.length() > 0) {
System.out.print(modifiers + " ");
}
System.out.print(name + "(");
// print parameter types
Class[] paramTypes = c.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0) {
System.out.print(", ");
}
System.out.print(paramTypes[j].getName());
}
System.out.println(") ;");
}
}
}
public static void printMethods(Class cl) {
Method[] methods = cl.getDeclaredMethods();
for (Method m : methods) {
Class retType = m.getReturnType();
String name = m.getName();
System.out.print(" ");
String modifiers = Modifier.toString(m.getModifiers());
if (modifiers.length() > 0) {
System.out.print(modifiers + " ");
}
System.out.print(retType.getName() + " " + name + "(");
Class[] paramTypes = m.getParameterTypes();
for (int j = 0; j < paramTypes.length; j++) {
if (j > 0) {
System.out.print(",");
}
System.out.print(paramTypes[j].getName());
}
System.out.println(");");
}
}
public static void printFields(Class cl) {
Field[] fields = cl.getDeclaredFields();
for (Field f : fields) {
Class type = f.getType();
String name = f.getName();
System.out.print(" ");
String modifiers = Modifier.toString(f.getModifiers());
if (modifiers.length() > 0) {
System.out.print(modifiers + " ");
System.out.println(type.getName() + " " + name + ";");
}
}
}
}
运行结果:
Enter class name (e.g. java.util.Date):
java.lang.Double
public final class java.lang.Double extends java.lang.Number implements java.lang.Comparable
{
public java.lang.Double(double) ;
public java.lang.Double(java.lang.String) ;
public boolean equals(java.lang.Object);
public static java.lang.String toString(double);
public java.lang.String toString();
public int hashCode();
public static int hashCode(double);
public static double min(double,double);
public static double max(double,double);
public static native long doubleToRawLongBits(double);
public static long doubleToLongBits(double);
public static native double longBitsToDouble(long);
public volatile int compareTo(java.lang.Object);
public int compareTo(java.lang.Double);
public byte byteValue();
public short shortValue();
public int intValue();
public long longValue();
public float floatValue();
public double doubleValue();
public static java.lang.Double valueOf(java.lang.String);
public static java.lang.Double valueOf(double);
public static java.lang.String toHexString(double);
public static int compare(double,double);
public static boolean isNaN(double);
public boolean isNaN();
public static boolean isInfinite(double);
public boolean isInfinite();
public static boolean isFinite(double);
public static double sum(double,double);
public static double parseDouble(java.lang.String);
public static final double POSITIVE_INFINITY;
public static final double NEGATIVE_INFINITY;
public static final double NaN;
public static final double MAX_VALUE;
public static final double MIN_NORMAL;
public static final double MIN_VALUE;
public static final int MAX_EXPONENT;
public static final int MIN_EXPONENT;
public static final int SIZE;
public static final int BYTES;
public static final java.lang.Class TYPE;
private final double value;
private static final long serialVersionUID;
}
2、泛型类和泛型方法
示例类
package com.lf.java.basic.generic;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 定义泛型类
*
* @param <T>
* @param <U>
*/
@AllArgsConstructor
@NoArgsConstructor
public class Pair<T, U> {
private T first;
private U second;
public T getFirst() {
return first;
}
public void setFirst(T first) {
this.first = first;
}
public U getSecond() {
return second;
}
public void setSecond(U second) {
this.second = second;
}
@Override
public String toString() {
return first +":"+ second;
}
public static <T> T getFirstPlus(T... a){
return a[2];
}
public static <T> Pair<T,T> getMiddle(T... a) {
return new Pair<>(a[0],a[1]);
}
/**
* 泛型通配符 子类
* @param p
*/
public static void printBuddies(Pair<? extends Comparable,? extends Comparable> p){
}
/**
* 泛型通配符 超类 Object
*/
public static <T extends Comparable<? super T>> T mini(T[] a){
return a[0];
}
/**
* 泛型限定,限定具有compareTo的方法的类
* @param a
* @param <T>
* @return
*/
public static <T extends Comparable & Serializable> T min(T[] a) // almost correct
{ if (a == null || a.length == 0) return null;
T smallest = a[0];
for (int i = 1; i < a.length; i++){
if (smallest.compareTo(a[i]) > 0) smallest = a[i];
}
return smallest;
}
public static <T> Pair<T, T> makePair(Class<T> cl) {
try {
return new Pair<>(cl.newInstance(),cl.newInstance());
} catch (Exception e) {
return null;
}
}
// 注意Class类本身是泛型。例如,String.daSS是一个Class<String> 的实例
// (事实上它是唯一的实例 。) 因此,makePair 方法能够推断出 pair 的类型。
public static void main(String[] args) {
Pair<String, Integer> p = new Pair();
p.setFirst("1");
p.setSecond(2);
System.out.println(p.toString());
String [] s ={"s","ss","sss","ssss","sssss"};
System.out.println(Pair.getFirstPlus(s));
//泛型向上推断,找出共同超类型为Number类型
Number firstPlus = Pair.getFirstPlus(3.14, 1729, 0);
System.out.println(firstPlus);
Serializable hello = Pair.getFirstPlus("Hello", 0, null);
System.out.println(hello);
Integer[] integers = {9,1,2,4,5,7};
System.out.println(Pair.min(integers));
//instanceof 和 getClass 只会指向原始类型Pair
// if (a instanceof Pair<String>) // Error
// Pair <String> stringPair = . .
// Pai <Employee> employeePair = . .
// if (stringPair.getClass() == employeePair.getClass()) // they are equal
// 使用会报错Pair<String>[] table = (Pair<String>[]) new Pair<?>[10];
// 可以使用ArrayList:ArrayList<Pair<String>>
//这个方法可以按照下列方式调用,获取pair对象:
Pair<String,String> pair = Pair.makePair(String.class);
System.out.println(pair.toString());
}
}
反射类
package com.lf.java.basic.reflect;
import java.lang.reflect.*;
import java.util.Arrays;
import java.util.Scanner;
public class GenericReflectionTest {
public static void main(String[] args) {
// read class name from command line args or user input
String name;
if (args.length > 0) name = args[0];
else {
try (Scanner in = new Scanner(System.in)) {
System.out.println("Enter class name (e.g. java.util .Collections): ");
name = in.next();
}
}
try {
Class<?> cl = Class.forName(name);
printClass(cl);
for (Method m : cl.getDeclaredMethods()) {
printMethod(m);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printClass(Class<?> cl) {
System.out.print(Modifier.toString(cl.getModifiers())+" "+cl);
printTypes(cl.getTypeParameters(), "<", ", ", ">", true);
Type sc = cl.getGenericSuperclass();
if (sc != null) {
System.out.print(" extends ");
printType(sc, false);
}
printTypes(cl.getGenericInterfaces(), " implements ", ", ", "", false);
System.out.println();
}
public static void printMethod(Method m) {
String name = m.getName();
System.out.print(Modifier.toString(m.getModifiers()));
System.out.print(" ");
printTypes(m.getTypeParameters(), "<", ", ", ">", true);
printType(m.getGenericReturnType(), false);
System.out.print(" ");
System.out.print(name);
System.out.print(" (");
printTypes(m.getGenericParameterTypes(), "", ", ", "", false);
System.out.println(")");
}
public static void printTypes(Type[] types, String pre, String sep, String suf,
boolean isDefinition) {
if (pre.equals(" extends ") && Arrays.equals(types, new Type[]{Object.class})) return;
if (types.length > 0) System.out.print(pre);
for (int i = 0; i < types.length; i++) {
if (i > 0) System.out.print(sep);
printType(types[i], isDefinition);
}
if (types.length > 0) System.out.print(suf);
}
public static void printType(Type type, boolean isDefinition) {
if (type instanceof Class) {
Class<?> t = (Class<?>) type;
System.out.print(t.getName());
} else if (type instanceof TypeVariable) {
TypeVariable<?> t = (TypeVariable<?>) type;
System.out.print(t.getName());
if (isDefinition) {
printTypes(t.getBounds(), " extends ", " & ", "", false);
}
} else if (type instanceof WildcardType) {
WildcardType t = (WildcardType) type;
System.out.print("?");
printTypes(t.getUpperBounds(), " extends ", " & ", "", false);
printTypes(t.getLowerBounds(), " super ", " & ", "", false);
} else if (type instanceof ParameterizedType) {
ParameterizedType t = (ParameterizedType) type;
Type owner = t.getOwnerType();
if (owner != null) {
printType(owner, false);
System.out.println(".");
}
printType(t.getRawType(), false);
printTypes(t.getActualTypeArguments(), "<", ", ", ">", false);
} else if (type instanceof GenericArrayType) {
GenericArrayType t = (GenericArrayType) type;
System.out.print("");
printType(t.getGenericComponentType(), isDefinition);
System.out.print("[]");
}
}
}
运行结果
Enter class name (e.g. java.util .Collections):
com.lf.java.basic.generic.Pair
public class com.lf.java.basic.generic.Pair<T, U> extends java.lang.Object
public void setFirst (T)
public static transient <T>T getFirstPlus (T[])
public static transient <T>com.lf.java.basic.generic.Pair<T, T> getMiddle (T[])
public static void printBuddies (com.lf.java.basic.generic.Pair<? extends java.lang.Comparable, ? extends java.lang.Comparable>)
public static <T extends java.lang.Comparable<? super T>>T mini (T[])
public void setSecond (U)
public static <T>com.lf.java.basic.generic.Pair<T, T> makePair (java.lang.Class<T>)
public static void main ([Ljava.lang.String;)
public java.lang.String toString ()
public static <T extends java.lang.Comparable & java.io.Serializable>T min (T[])
public T getFirst ()
public U getSecond ()