How to Check If Class Exists Somewhere in Package

How to check if class exists somewhere in package?

Not sure about android but in standard JDK you would do something like this:

try {
Class.forName( "your.fqdn.class.name" );
} catch( ClassNotFoundException e ) {
//my class isn't there!
}

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 {
Class<?> clazz = 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);
}

}

Output :

instance method with 5 and hello

static method with 5 and hello

If class exists, do something with Javascript

getElementsByClassName returns a NodeList which is an array-like object. You can check its length to determine if elements with defined class exist:

var isMobileVersion = document.getElementsByClassName('snake--mobile');
if (isMobileVersion.length > 0) {
// elements with class "snake--mobile" exist
}

How to determine if a class exists in the project

Use the class loader. Any class that is reachable from the same class loader as "FindClass" can be found. Remember to use the class's package name as part of the name: "package.class".

public class FindClass {

public boolean findClass(String className) {
try {
FindClass.class.getClassLoader().loadClass(className);
return true;
} catch (ClassNotFoundException e) {
return false;
}
}

An alternative to using the above classloader is to use the class loader that loaded the application.

Thread.currentThread().getContextClassLoader().loadClass(className);

Checking if the class exists on Page using Jquery

You need to add a dot to the test class

if ($('.test')[0]) {
$('h1').show();
} else {
$('h1').text('Class "Test" Does NOT Exist');
}

Check if class exists somewhere in parent

You'll have to do it recursively :

// returns true if the element or one of its parents has the class classname
function hasSomeParentTheClass(element, classname) {
if (element.className.split(' ').indexOf(classname)>=0) return true;
return element.parentNode && hasSomeParentTheClass(element.parentNode, classname);
}

Demonstration (open the console to see true)

IF this class exists, OR this class doesn't exist, do something with jQuery and submit form - but won't submit

I would use the .hasClass() method from jQuery to check if any size-attributes exist.

.on('click', '.modalAddToBagButton', function(e) {
e.preventDefault();
$form = $(this).closest("#dialog-addToBag").find('form');
if( $( ".es-value.selected" ).length || !$("li").hasClass("size-attribute")){
$form.submit();
} else {
$("#errormessage").show();
$("#error-border").addClass("error-border");
}
}

Java: Verify Class Exists

One advantage of Java is that you have a compiler, so usually this is a non-issue. If you compile your code properly and then, for some reason, drop a required jar file from the runtime environment, you'll get a java.lang.ClassNotFoundException, so that should be enough.

If you want to be super-extra-safe, you could try calling Class.forName:

@Test
public void testClassExists {
try {
Class.forName("org.mypackage.Car");
} catch (ClassNotFoundException e) {
Assert.fail("should have a class called Car");
}
}


Related Topics



Leave a reply



Submit