Use of Class.forName
Class.forName returns a class that uses this method to obtain a class
First, create a student class
1 /***2 * This Class was for Student Bean3 * @author Young4 *5 */6 Public classStudent {7 8 Private intstud_id;9 PrivateString Stud_name;Ten PrivateString sex; One PrivateString birthday; A PrivateString score; - - Public intgetstud_id () { the returnstud_id; - } - - Public voidSETSTUD_ID (intstud_id) { + This. stud_id =stud_id; - } + A PublicString Getstud_name () { at returnStud_name; - } - - Public voidsetstud_name (String stud_name) { - This. Stud_name =Stud_name; - } in - PublicString Getsex () { to returnsex; + } - the Public voidsetsex (String sex) { * This. Sex =sex; $ }Panax Notoginseng - PublicString Getbirthday () { the returnbirthday; + } A the Public voidsetbirthday (String birthday) { + This. Birthday =birthday; - } $ $ PublicString Getscore () { - returnscore; - } the - Public voidSetScore (String score) {Wuyi This. score =score; the } - Wu /** - * This method is a constructor About * $ * @author Young - * @paramID - * @paramname - * @paramSex A * @paramBirthday + * @paramscore the */ - PublicStudent (intID, string name, String sex, string birthday, $ String Score) { the the This. stud_id =ID; the This. Stud_name =name; the This. Sex =sex; - This. Birthday =birthday; in This. score =score; the } the About PublicStudent () { the the This. stud_id = 1000200; the This. Stud_name = "Test"; + This. Sex = "Male"; - This. Birthday = "2015/01/28"; the This. score = "3.3";Bayi } the}
View Code
Then use the class
class<?> C = Class.forName (Student. Class. Getcanonicalname ()); Object obj=c.newinstance (); for (Method m:c.getmethods ()) { System.out.println (M.getname ()); if (M.getname (). Equals ("GetId")) { System.out.println (M.invoke (obj)); }
To run a method of the class using Invoke
Get an object using the GetInstance method
Gets the object without parameters, and how can I get it if I encounter an object with parameters?
class<?> C = Class.forName (Student.class. Getcanonicalname ()); Constructor<?> constructor =C.getconstructor (Integer.type, String.class, String.class, String.class, String.class); Object obj= Constructor.newinstance (1, "Test", "Male", "2015-07-09", "80"); for(Method m:c.getmethods ()) {System.out.println (M.getname ()); if(M.getname (). Equals ("Getsex") ) {System.out.println (M.invoke (obj)); } }
With constructor, you can set parameters
Use of Class.forName