- import java.lang.reflect.Constructor;
- public class reflex {
- public static void main(String[] args)throws Exception
- {
- Person p1 = new Person("First");//注意 这样可以new
- Constructor cons = Person.class.getConstructor(String.class);//用反射居然就变成类似private的,必须加Declared
- Person p3 = (Person)cons.newInstance("Third");
-
- System.out.println(p1 + "+" + p3);
- }
- }
- class Person
- {
- private String pStr;
- public Person(String str)
- {
- pStr = str;
- }
-
- public String getName()
- {
- return pStr;
- }
-
- public void setName(String str)
- {
- pStr = str;
- }
-
- public String toString()
- {
- return pStr;
- }
- }
复制代码
|
|