Java/Reflection/Object

Материал из Java эксперт
Перейти к: навигация, поиск

Create an object from a string

 

public class Main {
  public static void main(String[] argv) throws Exception {
    Class[] classParm = null;
    Object[] objectParm = null;
    try {
      String name = "java.lang.String";
      Class cl = Class.forName(name);
      java.lang.reflect.Constructor co = cl.getConstructor(classParm);
      System.out.println(co.newInstance(objectParm));
    } catch (Exception e) {
      e.printStackTrace();
      
    }
  }
}





Determine the Superclass of an Object

 
import java.util.ArrayList;
public class Main {
  public static void main(String[] args) {
    System.out.println(new ArrayList().getClass().getSuperclass().getName());
  }
}
//java.util.AbstractList





Find the Package of an Object

 
import java.util.ArrayList;
import java.util.Vector;
public class Main {
  public static void main(String[] args) {
    System.out.println(new Vector().getClass().getPackage().getName());
    System.out.println(new ArrayList().getClass().getPackage().getName());
    System.out.println("Test String".getClass().getPackage().getName());
    System.out.println(new Integer(1).getClass().getPackage().getName());
  }
}
/*
java.util
java.util
java.lang
java.lang
*/





For the primitive tipe the interface will be an empty array

 
import java.util.Calendar;
import java.util.Date;
public class Main {
  public static void main(String[] args) {
    Date date = Calendar.getInstance().getTime();
    
    Class c = char.class;
    Class[] interfaces = c.getInterfaces();
    for (Class intf : interfaces) {
      System.out.println("Interface Name = " + intf.getName());
    }
  }
}





Get the class By way of an object

 
public class Main {
  public static void main(String[] argv) throws Exception {
    Object object = new String();
    // By way of an object
    Class cls = object.getClass();
  }
}





Get the fully-qualified name of a class

 

public class Main {
  public static void main(String[] argv) throws Exception {
    Class cls = java.lang.String.class;
    String name = cls.getName(); 
    System.out.println(name);
  }
}





Get the fully-qualified name of a inner class

 
public class Main {
  public static void main(String[] argv) throws Exception {
    Class cls = java.util.Map.Entry.class;
    String name = cls.getName(); 
    System.out.println(name);
  }
}





Get the name of an array

 
public class Main {
  public static void main(String[] argv) throws Exception {
    String name = boolean[].class.getName();
    System.out.println(name);
    name = byte[].class.getName();
    System.out.println(name);
    name = char[].class.getName();
    System.out.println(name);
    name = short[].class.getName();
    System.out.println(name);
    name = int[].class.getName();
    System.out.println(name);
    name = long[].class.getName();
    System.out.println(name);
    name = float[].class.getName();
    System.out.println(name);
    name = double[].class.getName();
    System.out.println(name);
    name = String[].class.getName();
    System.out.println(name);
    name = int[][].class.getName();
    System.out.println(name);
  }
}





Get the name of a primitive type

 
public class Main {
  public static void main(String[] argv) throws Exception {
    String name = int.class.getName(); // int
    System.out.println(name);
  }
}





Get the name of void

 
public class Main {
  public static void main(String[] argv) throws Exception {
    Class cls = Void.TYPE;
    String name = cls.getName(); // void
  }
}





Get the unqualified name of a class

 
public class Main {
  public static void main(String[] argv) throws Exception {
    Class cls = java.util.Map.Entry.class;
    String name = cls.getName();
    if (name.lastIndexOf(".") > 0) {
      name = name.substring(name.lastIndexOf(".") + 1); // Map$Entry
      name = name.replace("$", ".");      // Map.Entry
    }
  }
}





Getting the Superclass of a Class Object

 
public class Main {
  public static void main(String[] argv) throws Exception {
    Class cls = java.lang.String.class;
    Class sup = cls.getSuperclass(); // java.lang.Object
    cls = java.lang.Object.class;
    sup = cls.getSuperclass(); // null
  }
}





If a class object is an interface or a class

 
 
public class Main {
  public static void main(String[] args) {
    // Checking whether Cloneable is an interface or class
    Class clazz = Cloneable.class;
    boolean isInterface = clazz.isInterface();
    System.out.println("Is Interface = " + isInterface);
  }
}





Instantiate unknown class at runtime and call the object"s methods

 
import java.lang.reflect.Method;
public class Main {
  public static void main(String[] args) throws Exception {
    Class myclass = Class.forName("java.lang.String");
    Method[] methods = myclass.getMethods();
    //Object object = myclass.newInstance();
    for (int i = 0; i < methods.length; i++) {
      System.out.println(methods[i].getName());
      //System.out.println(methods[i].invoke(object));
    }
  }
}
/*
hashCode
compareTo
compareTo
indexOf
indexOf
indexOf
indexOf
equals
toString
charAt
codePointAt
codePointBefore
codePointCount
compareToIgnoreCase
concat
contains
contentEquals
contentEquals
copyValueOf
copyValueOf
endsWith
equalsIgnoreCase
format
format
getBytes
getBytes
getBytes
getBytes
getChars
intern
isEmpty
lastIndexOf
lastIndexOf
lastIndexOf
lastIndexOf
length
matches
offsetByCodePoints
regionMatches
regionMatches
replace
replace
replaceAll
replaceFirst
split
split
startsWith
startsWith
subSequence
substring
substring
toCharArray
toLowerCase
toLowerCase
toUpperCase
toUpperCase
trim
valueOf
valueOf
valueOf
valueOf
valueOf
valueOf
valueOf
valueOf
valueOf
getClass
wait
wait
wait
notify
notifyAll
*/





Obtain from where a Class is loaded

 
public class Main {
  public static void main(String args[]) {
    Main m = new Main();
    System.out.println(m.getClass().getName() + " is loaded from "
        + m.getClass().getProtectionDomain().getCodeSource().getLocation());
  }
}





Using Reflection to browse a java class

 

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Main {
  public static void main(String argv[]) throws Exception{
    String className = "String";
    Class c = Class.forName(className);
    Constructor cst[] = c.getDeclaredConstructors();
    // get fields from the Class object
    Field f[] = c.getDeclaredFields();
    // get methods from the Class object
    Method m[] = c.getDeclaredMethods();
    // filling the constructors list box
    for (int i = 0; i < cst.length; i++) {
      System.out.println(cst[i].getName());
    }
    // filling the fields list box
    for (int i = 0; i < f.length; i++) {
      System.out.println(f[i].getName());
    }
    // filling the methods list box
    for (int i = 0; i < m.length; i++) {
      System.out.println(m[i].getName());
    }
  }
}