没有合适的资源?快使用搜索试试~ 我知道了~
首页java中Class.forName方法的作用详解
java中Class.forName方法的作用详解
1.0k 浏览量
更新于2023-05-24
评论
收藏 60KB PDF 举报
Class.forName(xxx.xx.xx) 返回的是一个类,但Class.forName方法的作用到底是什么終?下面这篇文章就来给大家详细介绍了关于java中Class.forName方法的作用,文中介绍的非常详细,需要的朋友可以参考借鉴,下面来一起看看吧。
资源详情
资源评论
资源推荐

java中中Class.forName方法的作用详解方法的作用详解
Class.forName(xxx.xx.xx) 返回的是一个类,但Class.forName方法的作用到底是什么終?下面这篇文章就来给
大家详细介绍了关于java中Class.forName方法的作用,文中介绍的非常详细,需要的朋友可以参考借鉴,下面
来一起看看吧。
前言前言
在做JAVA EE开发的过程中,更多的是使用框架来提高开发效率.越来越发现,之前很基础的一些东西,都忘记的差不多了.从今天
开始慢慢的复习一下基础.今天在看JDBC的时候,就有一个有趣的地方,之前学的时候,也没在意.这个Class.forName究竟是什么鬼.
连接数据库几大步连接数据库几大步.看以下代码看以下代码
import com.mysql.jdbc.Driver;
import java.sql.*;
/**
* @author honway.liu
* @date 2016/12/8 下午11:07
* @email gm100861@gmail.com
* @blog http://linuxsogood.org
*/
public class JdbcDemo {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
String url = "jdbc:mysql://127.0.0.1:3306/mydb";
String username = "root";
String password = "redhat";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
String sql = "SELECT * FROM msg";
PreparedStatement prepareStatement = connection.prepareStatement(sql);
ResultSet resultSet = prepareStatement.executeQuery();
resultSet.next();
String address = resultSet.getString("address");
System.out.println(address);
}
}
其中第一步,搞的我有点想不通.为啥Class.forName传入了一段字符串之后,就知道我连接的数据库是mysql? 有点不科学
啊.Class.forName到底做了啥.下面就开始到源码中,一探究竟.
@CallerSensitive
public static Class<?> forName(String className)
throws ClassNotFoundException {
Class<?> caller = Reflection.getCallerClass();
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
发现它调用了forName0方法,继续跟踪再看看
private static native Class<?> forName0(String name, boolean initialize,
ClassLoader loader,
Class<?> caller)
throws ClassNotFoundException;
native方法,源码也只能到此结束了.看下官方文档,怎么说吧.
https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)
发现官方文档,还是描述的很清楚的.
Returns the Class object associated with the class or interface with the given string name,
using the given class loader.
Given the fully qualified name for a class or interface (in the same format returned by getName)
this method attempts to locate, load, and link the class or interface.
The specified class loader is used to load the class or interface.
If the parameter loader is null, the class is loaded through the bootstrap class loader.
The class is initialized only if the initialize parameter is true and if it has not been
initialized earlier.
嗯,描述的还算是很清楚.返回一个给定类或者接口的一个Class对象,如果没有给定classloader,那么会使用根类加载器.如
果initalize这个参数传了true,那么给定的类如果之前没有被初始化过,那么会被初始化.我们在JDBC第一步的时候,传入的参数
是com.mysql.jdbc.Driver. 也就是说这个类会被初始化.我们看一下这个类里面的内容.



















安全验证
文档复制为VIP权益,开通VIP直接复制

评论0