public Class<Example>getExampleByInstance(){
Example example =newExample();// getClass是Object类里面的方法;《?》 是通配符
Class<?> clazz = example.getClass();return(Class<Example>)clazz;}
//根据传递的参数创建类的对象:initargs 构造方法参数public T newInstance(Object... initargs)
1根据class创建对象
//方式一 clazz.newInstance()
Class<Example> clazz = Example.class;
Example example = clazz.newInstance();//方式二 先获取再由Constructor:clazz.getConstructors()/getConstructor(...) //再由Constructor.newInstance 方法构造对象-----------------------------------------publicclassExample{
privateint value;publicExample(){
}// 如果只声明有参构造函数,clazz.newInstance()会报错publicExample(Integer value){
this.value = value;}staticpublicvoidmain(String[] args)throws Exception{
Class<Example> clazz = Example.class;//根据指定构造函数参数获取Constructor
Constructor<Example> constructor = clazz.getConstructor(Integer.class);
Example example = constructor.newInstance(100);
System.out.println(example.value);}}
2由class获取Field,并操作实例的属性
publicclassExample{
privateint value , count;staticpublicvoidmain(String[] args)throws Exception{
Class<Example> clazz = Example.class;//获取所有的属性,getField只能获取public的属性
Field[] fs = clazz.getDeclaredFields();//根据名称获取指定 Field
Field value = clazz.getDeclaredField("value");
Example example = clazz.newInstance();//使用反射机制可以打破封装性,导致了java对象的属性不安全
value.setAccessible(true);//setAccessible(true)让private的参数可赋值操作//由Field反过去设置example的值
value.set(example,100);
System.out.println(example.value);}}