JavaのClassNotFoundExceptionは、java.lang.ClassNotFoundExceptionというエラーです。

JavaのClassNotFoundException

  • Java ClassNotFoundException occurs when the application tries to load a class but Classloader is not able to find it in the classpath.
  • Common causes of java.lang.ClassNotFoundException are using Class.forName or ClassLoader.loadClass to load a class by passing String name of a class and it’s not found on the classpath.
  • ClassNotFoundException is a checked exception, so it has to be catch or thrown to the caller.
  • ClassNotFoundException always occurs at runtime because we are indirectly loading the class using Classloader. Java compiler has no way to know if the class will be present in the classpath at runtime or not.
  • One of the most common example of ClassNotFoundException is when we try to load JDBC drivers using Class.forName but forget to add it’s jar file in the classpath.

JavaのClassNotFoundExceptionの例

簡単な例を見て、ClassNotFoundExceptionが発生する場合を見てみましょう。

package com.scdev.exceptions;

public class DataTest {

  public static void main(String[] args) {
    try {
      Class.forName("com.scdev.MyInvisibleClass");

      ClassLoader.getSystemClassLoader().loadClass("com.scdev.MyInvisibleClass");

      ClassLoader.getPlatformClassLoader().loadClass("com.scdev.MyInvisibleClass");
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }

}

上記のプログラムを実行すると、com.scdev.MyInvisibleClassが存在しないことに注意してください。その結果、以下の例外のスタックトレースが表示されます。

java.lang.ClassNotFoundException: com.scdev.MyInvisibleClass
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)
	at java.base/java.lang.Class.forName0(Native Method)
	at java.base/java.lang.Class.forName(Class.java:292)
	at com.scdev.exceptions.DataTest.main(DataTest.java:7)

上記の例では、すべての3つの文がjava.lang.ClassNotFoundExceptionをスローします。

ClassNotFoundExceptionを解決する方法

ClassNotFoundExceptionを修正するのは非常に簡単です。なぜなら、例外のスタックトレースが明確にクラスが見つからないことを示しているからです。クラスパスの設定を確認して、実行時にクラスが存在することを確認するだけです。

ClassNotFoundExceptionとNoClassDefFoundErrorの違いについて説明します。

NoClassDefFoundErrorは、実行時にクラスが見つからないときに発生するランタイムエラーです。ClassNotFoundExceptionと非常に似ています。詳しくはJava NoClassDefFoundErrorを参照してください。参考:APIドキュメント

コメントを残す 0

Your email address will not be published. Required fields are marked *