- Java check if class exists
- Java check if class exists
- Java: check if a class exists and call a specific method if it exists
- Java Classes and Objects
- Java Classes/Objects
- Create a Class
- Create an Object
- Multiple Objects
- Using Multiple Classes
- Проверка существования класса в Java
- 2. Использование Class.forName()
- 2.1. Когда ожидать ClassNotFoundException
- 2.2. Побочный эффект: инициализация класса
- 3. Указание Class.forName() пропустить инициализацию
- 4. Модули Java 9
- 5. Вывод
- Java: check if a class exists and call a specific method if it exists
- Solution 2
- Solution 3
- Solution 4
- Solution 5
Java check if class exists
To create an object of , specify the class name, followed by the object name, and use the keyword : Example Create an object called » » and print the value of x: Try it Yourself » Multiple Objects You can create multiple objects of one class: Example Create two objects of : Try it Yourself » Using Multiple Classes You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the method (code to be executed)).
Java check if class exists
boolean is_subclass = Superclass.class.isAssignableFrom(Subclass.class); // example: // List.class.isAssignableFrom(LinkedList.class) is true // List.class.isAssignableFrom(HashMap.class) is false
How to check if class in java Code Example, boolean is_subclass = Superclass.class.isAssignableFrom(Subclass.class); // example: // List.class.isAssignableFrom(LinkedList.class) is true // List.class
Java: check if a class exists and call a specific method if it exists
Is there a way to do the following? check if a class exists (in the same package) and if it does exist, check if a particular method exists, and if so, calling it?
Say that I have class X. In some method of class X, I want to do the following:
Is such a thing possible? And is doing such a thing reasonable? Thanks.
Is such a thing possible? And is doing such a thing reasonable? Thanks.
Of course it is possible.
If you develop a program or a library that has to discover dynamically some classes, it is a very reasonable thing.
If it is not the case, it could not be.
If your need makes sense, you should ask you an additional question : should you invoke a static or instance method ?
Here is a sample example with both solutions :
ReflectionClass that contains the logic using reflection :
import java.lang.reflect.Method; public class ReflectionCalls < public static void main(String[] args) < new ReflectionCalls(); >public ReflectionCalls() < callMethod(true); callMethod(false); >private void callMethod(boolean isInstanceMethod) < String className = "DiscoveredClass"; String staticMethodName = "methodStatic"; String instanceMethodName = "methodInstance"; Class[] formalParameters = < int.class, String.class >; Object[] effectiveParameters = new Object[] < 5, "hello" >; String packageName = getClass().getPackage().getName(); try < Classclazz = Class.forName(packageName + "." + className); if (!isInstanceMethod) < Method method = clazz.getMethod(staticMethodName, formalParameters); method.invoke(null, effectiveParameters); >else < Method method = clazz.getMethod(instanceMethodName, formalParameters); Object newInstance = clazz.newInstance(); method.invoke(newInstance, effectiveParameters); >> catch (Exception e) < e.printStackTrace(); >> >
DiscoveredClass (the class we manipulate in the example)
package reflectionexp; public class DiscoveredClass < public static void methodStatic(int x, String string) < System.out.println("static method with " + x + " and " + string); >public void methodInstance(int x, String string) < System.out.println("instance method with " + x + " and " + string); >>
instance method with 5 and hello
static method with 5 and hello
Yes, this can be done. I’ve created a Test class in the same Package as the current class.
import java.lang.reflect.Method; public class Sample < public static void main(String[] args) < Classclazz = null; try < clazz = Class.forName("Test"); >catch (ClassNotFoundException e) < // TODO Auto-generated catch block e.printStackTrace(); >if (clazz == null) < System.out.println("class not found. Go eat some waffles and correct the name"); return; >Method m = null; try < m = clazz.getMethod("foo", null); >catch (NoSuchMethodException | SecurityException e) < // TODO Auto-generated catch block e.printStackTrace(); >if (m == null) < System.out.println("method not found. Go eat some waffles and correct the name"); return; >Test t; try < t = (Test) clazz.newInstance(); m.invoke(t, null); >catch (Exception e) < // TODO Auto-generated catch block e.printStackTrace(); >> > public class Test < static < System.out.println("test. "); >public void foo() < System.out.println("foo"); >>
try < Class yourClass = Class.forName( "classname" ); Object o = yourClass.newInstance(); >catch( ClassNotFoundException e ) < //Throw error or whatever >
To check if a method exists you could use the NoSuchMethodError e in a try/catch
You can do this using reflection, however it isnt really practical unless you are trying to access classes that potentially will not be present at runtime or if you are trying to access private or hidden fields. Example below.
public static void reflectionDemo() < //Here we attempt to get the common URI class //If it is found, we attempt to get the create method //We then invoke the create method and print the class name of the result. try < ClassuriClass = Class.forName("java.net.URI"); //getMethod(String name, Class. args); java.lang.reflect.Method create = uriClass.getMethod("create", String.class); //The first parameter is null because this is a static method. //invoke(Object target, Object. args); System.out.println(create.invoke(null, "some/uri").getClass()); //Will print class java.net.URI > catch (ClassNotFoundException e) < // If class doesnt exist e.printStackTrace(); >catch (NoSuchMethodException e) < // If method doesnt exist e.printStackTrace(); >catch (SecurityException e) < // See Javadoc e.printStackTrace(); >catch (IllegalAccessException e) < // From invoke e.printStackTrace(); >catch (IllegalArgumentException e) < // From invoke e.printStackTrace(); >catch (java.lang.reflect.InvocationTargetException e) < // From invoke e.printStackTrace(); >>
Java check if class exists Code Example, how to check if an object is of a certain class java. java check if object is instance of class. java check if variable is a specific class. check if …
Java Classes and Objects
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes , such as weight and color, and methods , such as drive and brake.
A Class is like an object constructor, or a «blueprint» for creating objects.
Create a Class
To create a class, use the keyword class :
Main.java
Create a class named » Main » with a variable x:
Remember from the Java Syntax chapter that a class should always start with an uppercase first letter, and that the name of the java file should match the class name.
Create an Object
In Java, an object is created from a class. We have already created the class named Main , so now we can use this to create objects.
To create an object of Main , specify the class name, followed by the object name, and use the keyword new :
Example
Create an object called » myObj » and print the value of x:
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main :
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method (code to be executed)).
Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory/folder:
Main.java
Second.java
When both files have been compiled:
You will learn much more about classes and objects in the next chapters.
Reflection — Java: check if a class exists and call a, If your need makes sense, you should ask you an additional question : should you invoke a static or instance method ? Here is a sample example with …
Проверка существования класса в Java
Проверка существования класса может быть полезна при определении используемой реализации интерфейса. Этот метод обычно используется в старых установках JDBC.
В этом руководстве мы рассмотрим нюансы использования Class.forName() для проверки существования класса в пути к классам Java .
2. Использование Class.forName()
Мы можем проверить существование класса с помощью Java Reflection , в частности, Class.forName() . Документация показывает, что если класс не может быть найден, будет выброшено исключение ClassNotFoundException .
2.1. Когда ожидать ClassNotFoundException
Во-первых, давайте напишем тест, который обязательно вызовет ClassNotFoundException , чтобы мы могли знать, что наши положительные тесты безопасны:
@Test(expected = ClassNotFoundException.class) public void givenNonExistingClass_whenUsingForName_thenClassNotFound() throws ClassNotFoundException Class.forName("class.that.does.not.exist"); >
Итак, мы доказали, что несуществующий класс вызовет исключение ClassNotFoundException . Давайте напишем тест для действительно существующего класса:
@Test public void givenExistingClass_whenUsingForName_thenNoException() throws ClassNotFoundException Class.forName("java.lang.String"); >
Эти тесты доказывают, что запуск Class.forName() без перехвата ClassNotFoundException эквивалентен указанному классу, существующему в пути к классам . Однако это не совсем идеальное решение из-за побочных эффектов .
2.2. Побочный эффект: инициализация класса
Важно отметить, что без указания загрузчика класса Class.forName() должен запустить статический инициализатор в запрошенном классе . Это может привести к неожиданному поведению.
Чтобы проиллюстрировать это поведение, давайте создадим класс, который генерирует исключение RuntimeException при выполнении его статического блока инициализатора, чтобы мы могли сразу узнать, когда он выполняется:
public static class InitializingClass static if (true) //enable throwing of an exception in a static initialization block throw new RuntimeException(); > > >
Из документации forName() мы можем видеть , что он выдает ошибку ExceptionInInitializerError , если инициализация, вызванная этим методом, не удалась.
Давайте напишем тест, который будет ожидать ExceptionInInitializerError при попытке найти наш InitializingClass без указания загрузчика классов:
@Test(expected = ExceptionInInitializerError.class) public void givenInitializingClass_whenUsingForName_thenInitializationError() throws ClassNotFoundException Class.forName("path.to.InitializingClass"); >
Поскольку выполнение статического блока инициализации класса является невидимым побочным эффектом, теперь мы можем видеть, как это может вызвать проблемы с производительностью или даже ошибки. Давайте посмотрим, как пропустить инициализацию класса.
3. Указание Class.forName() пропустить инициализацию
К счастью для нас, существует перегруженный метод forName(), который принимает загрузчик класса и указывает, следует ли выполнять инициализацию класса.
Согласно документации следующие вызовы эквивалентны:
Class.forName("Foo") Class.forName("Foo", true, this.getClass().getClassLoader())
Изменив true на false , теперь мы можем написать тест, который проверяет существование нашего класса InitializingClass , не вызывая его статический блок инициализации :
@Test public void givenInitializingClass_whenUsingForNameWithoutInitialization_thenNoException() throws ClassNotFoundException Class.forName("path.to.InitializingClass", false, getClass().getClassLoader()); >
4. Модули Java 9
Для проектов Java 9+ существует третья перегрузка Class.forName() , которая принимает имя класса Module и String . Эта перегрузка не запускает инициализатор класса по умолчанию. Кроме того, в частности, он возвращает null , когда запрошенный класс не существует, а не создает исключение ClassNotFoundException .
5. Вывод
В этом кратком руководстве мы рассмотрели побочный эффект инициализации класса при использовании Class.forName() и обнаружили, что вы можете использовать перегрузки forName() , чтобы предотвратить это.
Исходный код со всеми примерами из этого руководства можно найти на GitHub .
Java: check if a class exists and call a specific method if it exists
Is such a thing possible? And is doing such a thing reasonable? Thanks.
Of course it is possible.
If you develop a program or a library that has to discover dynamically some classes, it is a very reasonable thing.
If it is not the case, it could not be.
If your need makes sense, you should ask you an additional question : should you invoke a static or instance method ?
Here is a sample example with both solutions :
ReflectionClass that contains the logic using reflection :
import java.lang.reflect.Method; public class ReflectionCalls < public static void main(String[] args) < new ReflectionCalls(); >public ReflectionCalls() < callMethod(true); callMethod(false); >private void callMethod(boolean isInstanceMethod) < String className = "DiscoveredClass"; String staticMethodName = "methodStatic"; String instanceMethodName = "methodInstance"; Class[] formalParameters = < int.class, String.class >; Object[] effectiveParameters = new Object[] < 5, "hello" >; String packageName = getClass().getPackage().getName(); try < Classclazz = Class.forName(packageName + "." + className); if (!isInstanceMethod) < Method method = clazz.getMethod(staticMethodName, formalParameters); method.invoke(null, effectiveParameters); >else < Method method = clazz.getMethod(instanceMethodName, formalParameters); Object newInstance = clazz.newInstance(); method.invoke(newInstance, effectiveParameters); >> catch (Exception e) < e.printStackTrace(); >> >
DiscoveredClass (the class we manipulate in the example)
package reflectionexp; public class DiscoveredClass < public static void methodStatic(int x, String string) < System.out.println("static method with " + x + " and " + string); >public void methodInstance(int x, String string) < System.out.println("instance method with " + x + " and " + string); >>
instance method with 5 and hello
static method with 5 and hello
Solution 2
Yes, this can be done. I’ve created a Test class in the same Package as the current class.
import java.lang.reflect.Method; public class Sample < public static void main(String[] args) < Classclazz = null; try < clazz = Class.forName("Test"); >catch (ClassNotFoundException e) < // TODO Auto-generated catch block e.printStackTrace(); >if (clazz == null) < System.out.println("class not found. Go eat some waffles and correct the name"); return; >Method m = null; try < m = clazz.getMethod("foo", null); >catch (NoSuchMethodException | SecurityException e) < // TODO Auto-generated catch block e.printStackTrace(); >if (m == null) < System.out.println("method not found. Go eat some waffles and correct the name"); return; >Test t; try < t = (Test) clazz.newInstance(); m.invoke(t, null); >catch (Exception e) < // TODO Auto-generated catch block e.printStackTrace(); >> > public class Test < static < System.out.println("test. "); >public void foo() < System.out.println("foo"); >>
Solution 3
try < Class yourClass = Class.forName( "classname" ); Object o = yourClass.newInstance(); >catch( ClassNotFoundException e ) < //Throw error or whatever >
To check if a method exists you could use the NoSuchMethodError e in a try/catch
Solution 4
You can do this using reflection, however it isnt really practical unless you are trying to access classes that potentially will not be present at runtime or if you are trying to access private or hidden fields. Example below.
public static void reflectionDemo() < //Here we attempt to get the common URI class //If it is found, we attempt to get the create method //We then invoke the create method and print the class name of the result. try < ClassuriClass = Class.forName("java.net.URI"); //getMethod(String name, Class. args); java.lang.reflect.Method create = uriClass.getMethod("create", String.class); //The first parameter is null because this is a static method. //invoke(Object target, Object. args); System.out.println(create.invoke(null, "some/uri").getClass()); //Will print class java.net.URI > catch (ClassNotFoundException e) < // If class doesnt exist e.printStackTrace(); >catch (NoSuchMethodException e) < // If method doesnt exist e.printStackTrace(); >catch (SecurityException e) < // See Javadoc e.printStackTrace(); >catch (IllegalAccessException e) < // From invoke e.printStackTrace(); >catch (IllegalArgumentException e) < // From invoke e.printStackTrace(); >catch (java.lang.reflect.InvocationTargetException e) < // From invoke e.printStackTrace(); >>
Solution 5
To find whether a class exists, you can use the forName() method on Class. To find whether a method exists, you can use the getMethod() method on Class. Documentation here:
For your class problem, you’d want to use code like:
try < Class.forName("Y"); >catch (ClassNotFoundException e)
For your method problem, you’d want to use code like:
try < Class.getMethod(a); >catch (NoSuchMethodException e)