Java中Class.forName和ClassLoader的区别?

【反射中,Class.forName和ClassLoader区别】 阅读详情

类的加载方式有多种,但是他们之间的区别和联系你知道吗?以前学习没太注意,还是记录下来,以后方便学习。

相同点:
Java中Class.forName和classloader都可以用来对类进行加载。

不同点:
a).Class.forName除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块。

b).而classloader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行static块。

c).Class.forName(name,initialize,loader)带参数也可控制是否加载static块。并且只有调用了newInstance()方法采用调用构造函数,创建类的对象。

首先先看下ClassForName的源码:
在这里插入图片描述

再来看下ClassLoader的源码:
在这里插入图片描述

分析 Class.forName()和ClassLoader.loadClass

Class.forName(className)方法,内部实际调用的方法是  Class.forName(className,true,classloader);

第2个boolean参数表示类是否需要初始化,  Class.forName(className)默认是需要初始化。

一旦初始化,就会触发目标对象的 static块代码执行,static参数也也会被再次初始化。 ClassLoader.loadClass(className)方法,内部实际调用的方法是 ClassLoader.loadClass(className,false); 第2个 boolean参数,表示目标对象是否进行链接,false表示不进行链接,由上面介绍可以,

不进行链接意味着不进行包括初始化等一些列步骤,那么静态块和静态对象就不会得到执行

直接上测试代码块:

代码块ClassA
在这里插入图片描述

代码块ClassB:
在这里插入图片描述

下边是测试代码(写的比较挤):
在这里插入图片描述

小伙伴们,你们的答案和我的是否一致呢?
来看下:
在这里插入图片描述

刚好验证了我们所说的结果,ClassForName才会走静态代码块

文章来源网络,版权归作者本人所有,如侵犯到原作者权益,请与我们联系删除或授权事宜
如果有误,请联系作者更改,谢谢,本人微信:void666666

面试官:Java中Class.forName和ClassLoader到底有啥区别? 最近在面试过程中有被问到,在Java反射中Class.forName()加载类和使用ClassLoader加载类的区别。当时没有想出来后来自己研究了一下就写下来记录一下。 阅读详情

相关推荐

STK新手必看:用700km轨道卫星,5步搞定对地覆盖分析报告

本文为STK新手提供700km轨道卫星对地覆盖分析的5步实操指南,涵盖卫星创建、传感器配置、区域定义、计算设置及报告生成全流程,特别标注常见操作误区与优化技巧,帮助用户快速掌握STK覆盖性分析核心方法。

weixin_42546392的博客 376

class.forname和classloader区别

网上能找到讲class.forname和classloader区别的一堆文章,但多数不是自己想要的,结合别人和自己的分析,重新整理下class.forname和classloader二者区别。 说到class.forname和classloader二者,必须先要了解java类的装载过程。 java类的装载过程 1. 加载 类的加载主要干三件事 通过类的全限定名来获取定义此类的二进制字节流 将这个类字节流代表的静态存储结构转为方法区的运行时数据结构 在堆中生成一个代表此类的java.lang.C

L13763338360的博客 4937

【国民技术N32项目移植】基于 Windows 的 ARM GCC 开发环境

【国民技术N32项目移植】基于 Windows 的 ARM GCC 开发环境

weixin_42150032的博客 1361

Class.forName()用法详解

主要功能 Class.forName(xxx.xx.xx)返回的是一个类 Class.forName(xxx.xx.xx)的作用是要求JVM查找并加载指定的类, 也就是说JVM会执行该类的静态代码段 下面,通过解答以下三个问题的来详细讲解下Class.forName()的用法。 一.什么时候用Class.forName()? 先来个热身,给你一个字符串变量,它代表一个类的包名和类名,你怎么实

Kaiwii的专栏 13万+

树莓派使用 OLED 屏显示图片及文字

树莓派默认是不带显示屏的,如果想要查看系统的一些信息,需要使用电脑登录到树莓派,或者通过 HDMI 连接外接显示器查看。这样做总是有点麻烦,我们可以通过外接一个 OLED 屏来显示一些关键参数或者图片。本文将详细介绍操作方法。 OLED 模组介绍 OLED 屏主要有两种:128×32 和 128×64 ,主要颜色是白、黄、蓝。OLED 屏的特点是功耗低,价格便宜,使用 I2C 接口与主机连接。本文所使用的是 128×64 尺寸的屏幕,外形如下: [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直

码到成功 3743

从零构建OpenBMC风扇控制:基于phosphor-pid-control的实战配置指南

本文详细介绍了如何从零开始构建OpenBMC风扇控制系统,基于phosphor-pid-control框架实现风扇自动调速。通过解析PID算法配置、传感器定义及控制区域设置,提供工业级散热解决方案,帮助开发者优化服务器能效与可靠性。

weixin_29263201的博客 748

ClassLoader和ClassForname的区别(详解)

一、概述  1.clssLoader和classForName都是用来加载类的,但是这两个方法一般却又在不同的场景使用。    如classLoader一般是spring容器用来加载bean的时候使用的,而classForName一般我们都是在使用数据库驱动的时候会使用该方法。  2.了解了两个加载类的不同场景之外后,先看一下类加载的过程。 2.1 .class文件首先被加载到j...

qq_35151346的博客 2121

深度学习|卷积神经网络

介绍卷积神经网络基本理论,包括卷积层、池化层和全连接层,并阐述LeNet卷积神经网络的构建过程。

weixin_58243219的博客 5727

Java反射中,Class.forName和ClassLoader的区别

一、区别 java类装载过程分为3步: 1、加载 Jvm把class文件字节码加载到内存中,并将这些静态数据装换成运行时数据区中方法区的类型数据,在运行时数据区堆中生成一个代表这个类的java.lang.Class对象,作为方法区类数据的访问入口。 *注:方法区不仅仅是存放方法,它存放的是类的类型信息。 2、链接:执行下面的校验、准备和解析步骤,其中解析步骤是可选的 a:校验:检查加载的clas...

riemann_的博客 5919

STM32硬件SPI调试ADS1256的3个致命坑,CubeMX配置避坑指南

本文深入解析STM32硬件SPI调试ADS1256高精度ADC芯片时常见的3大配置陷阱,包括SPI时钟频率、时钟极性与相位、数据字节序等关键问题。通过CubeMX实战配置指南和实测数据对比,提供稳定可靠的解决方案,帮助开发者避免常见错误,提升采样精度和系统稳定性。

weixin_42550597的博客 346

Claude Code 处理长任务 + Cursor 专注交互:双栈协作的 3 种分工场景与响应提速 35% 实测

揭示 Claude Code 与 Cursor 在 AI 编程中的本质分工:Claude Code 作为离线式架构师处理跨文件、带约束的长链路重构(如单体拆微服务),Cursor 作为现场交互工程师专注秒级局部编辑;提出按任务切片动态切换的三种工程化协作场景,并给出结构化上下文构建、约束型 Prom

weixin_28728443的博客 123

Java中Class.forName和ClassLoader到底有啥区别

Java中Class.forName和ClassLoader到底有啥区别

【可全包】本人程序员,不需要做任何吹嘘,只是实在写点程序,写点文档,熟悉各类主流框架,SSM,SpringBoot,Flask,Djiango,Mysql,Sqlite,VUE,Uniapp等,各类程序设计专家,优质作者 683

【系统架构设计师】十、统一建模语言UML(基本概念|UML2.0|SysML)

UML 2.0 提供了 14 种图,分别是类图、对象图、用例图、序列图、通信图(协作图)、状态图、活动图、构件图(组件图)、部署图、制品图、组合结构图、包图、交互概览图和计时图(定时图)。序列图、通信图、交互概览图和计时图均被称为交互图。 系统建模语言(SysML)是一种通用图形建模语言,用于指定,分析,设计和验证可能包括硬件,软件,信息,人员,程序和设施的复杂系统。特别是,该语言提供了图形表示,其具有用于建模系统需求,行为,结构和参数的语义基础,用于与其他工程分析模型集成。

帅次的博客 2522

在Java的反射中,Class.forName和ClassLoader的区别

在Java反射中Class.forName()加载类和使用ClassLoader加载类的区别。解释 在java中Class.forName()和ClassLoader都可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“通过一个类的全限定名来获取描述此类的二进制字节流”,获取到二进制流后放到JVM中。Class.forName()方法实际上也...

matinal 當冬夜漸暖 。公众号:matinal 286

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Java 反射中,class.forName()和classLoader的区别

1、java中class.forName()和classLoader都可用来对类进行加载。不同:1)class.forName()除了将类的.class文件加载到jvm中之外,还会对类进行解释,执行类中的static块,还会执行给静态变量赋值的静态方法 2)classLoader只干一件事情,就是将.class文件加载到jvm中,不会执行static中的内容,只有在newInstance才会去执行

初心未改 7902

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

在 Java 的反射中,Class.forName 和 ClassLoader 的区别

在java中Class.forName()和ClassLoader都可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“通过一个类的全限定名来获取描述此类的二进制字节流”,获取到二进制流后放到JVM中。Class.forName()方法实际上也是调用的CLassLoader来实现的。 Class.forName(String classNam...

hupoling的专栏 9万+

在java反射中,Class.forName()和ClassLoader的区别

前言: 最近在面试过程中有被问到,在Java反射中Class.forName()加载类和使用ClassLoader加载类的区别。当时没有想出来后来自己研究了一下就写下来记录一下。 解释: 在java中Class.forName()和ClassLoader都可以对类进行加载。ClassLoader就是遵循双亲委派模型最终调用启动类加载器的类加载器,实现的功能是“通过一个类的全限定名来获取描述此...

jiankangzhu的博客 291
上一篇: IDEA常用快捷键总结【特别全】
下一篇: nginx全部知识(让你穷光蛋秒变负二代,Come on!)
wt520it
博客等级 码龄8年 69粉丝 72原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值