多说无益,直接上代码:
首先重写InvocationHandler类:
public class MapperProxyInvocationHandler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//这里写主要的功能强化逻辑与调用业务方法
//其中Method method代表传过来的业务方法,而Object[] args代表传过来的参数,可以用args[n]来调用参数
Object obj = method.invoke(delegate,args); //此处是调用业务方法,而Object obj是方法返回值
return obj;
}
}
业务接口:
public interface UserMapper {
User selectById(int id);
}
业务接口实现类:
public interface UserMapperImpl {
User selectById(int id){
return new User();
}
}
测试类:
public class test{
public static void main(String[] args){
//先获取需要代理的目标类
UserMapper userMapper = new UserMapperImpl();
//Proxy.newProxyInstance()方法可以得到一个代理类对象
userMapper = (UserMapper) Proxy.newProxyInstance(
userMapper.getClass().getClassLoader(),
userMapper.getClass().getInterfaces(),
new MapperProxyInvocationHandler());
userMapper.selectById(1);
}
}
如果我没有业务方法的实现类也可以:
首先重写InvocationHandler类:
public class MapperProxyInvocationHandler implements InvocationHandler{
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//一下是对数据库的操作
String driver = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://127.0.0.1:3306/?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=utf-8";
String username = "";
String password = "";
String sql = "select * from user where id="+args[0];
System.out.println(sql);
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
User user = new User();
try {
Class.forName(driver);
connection = DriverManager.getConnection(url,username,password);
statement = connection.prepareStatement(sql);
resultSet = statement.executeQuery();
if (resultSet.next()){
user.setId(Integer.parseInt(resultSet.getString("id")));
user.setName(resultSet.getString("name"));
user.setAge(Integer.parseInt(resultSet.getString("age")));
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
//这里把查到的数据封装成User对象返回回去
return user;
}
}
业务接口:
public interface UserMapper {
User selectById(int id);
}
测试类:
public class test {
public static void main(String[] args) {
UserMapper userMapper = (UserMapper) Proxy.newProxyInstance(
//这里直接把接口的ClassLoader返回回去
UserMapper.class.getClassLoader(),
//这里本来是返回业务接口实现类所实现的业务接口,由于现在这里就是接口,直接返 回去就行了
new Class[]{UserMapper.class},
new MapperProxyInvocationHandler());
System.out.println(userMapper.selectById(1));
}
}
这里用jdk动态代理封装了一个jdbc的查询单条记录功能。