首页 > 代码库 > Java中反射的三种常用方式

Java中反射的三种常用方式

Java中反射的三种常用方式

package com.xiaohao.test;


public class Test{
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
// Class<?> clazz=Class.forName("com.xiaohao.test.User"); //1方法一
// User user=(User) clazz.newInstance();

// User user=User.class.newInstance(); //2 方法二

User user2=new User(); //3 方法三
User user=user2.getClass().newInstance();
user.setId(10);
user.setUserName("小浩");
user.setPassword("123456");
System.out.println(user);

}
}

 

 

package com.xiaohao.test;

import java.util.ArrayList;
import java.util.List;

public class User {
private Integer id;
private String userName;
private String password;
List<String> books=new ArrayList<String>();



public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}

public User() {
super();
}

public List<String> getBooks() {
return books;
}

public void setBooks(List<String> books) {
this.books = books;
}

@Override
public String toString(){
return this.id+" "+this.userName+" "+this.password+" ";
}

 

}

 

 

 

 

 

 

package com.xiaohao.test;

import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;


public class Test{
public static void main(String[] args) throws Exception {
// Class<?> clazz=Class.forName("com.xiaohao.test.User"); //1方法一
// User user=(User) clazz.newInstance();

// User user=User.class.newInstance(); //2 方法二

User user2=new User(); //3 方法三
User user=user2.getClass().newInstance();
System.out.println("user2对象的值为:"+user2);
System.out.println("类的名字为:"+user2.getClass().getName());
// Field field=user2.getClass().getDeclaredField("number");
// Field field=User.class.getDeclaredField("number");
Field field=Class.forName("com.xiaohao.test.User").getDeclaredField("number");
field.setAccessible(true);
field.set(user2,"1000");
System.out.println("user2对象的值为:"+user2);
Method method=User.class.getDeclaredMethod("setUserName",String.class);
method.invoke(user2,"小浩爷爷");
System.out.println("user2对象的值为:"+user2);
Class<?> component=Class.forName("com.xiaohao.test.User").getDeclaredField("address").get(user2).getClass().getComponentType();
User.class.getDeclaredField("address").setAccessible(true);
int length=((String[])User.class.getDeclaredField("address").get(user2)).length;
System.out.println("user2中原始的数组的长度为:"+length);
Object [] array=(Object[]) Array.newInstance(component, length+75);
System.out.println("user2中修改后的数组的长度为:"+array.length);
user.setId(10);
user.setUserName("小浩");
user.setPassword("123456");
System.out.println(user);

}
}

Java中反射的三种常用方式