I am writing a method were I would like to pass a class to a method, where a part of the code includes checking if the object is of a certain type. This is what I want (but which obviously doesn't work):
private static class MyClass1 { /***/ }
private static class MyClass2 { /***/ }
private void someFunc() {
/* some code */
methodName(MyClass1);
methodName(MyClass2);
}
private void methodName(Class myClass) {
Object obj;
/* Complicated code to find obj in datastructure */
if (obj instanceof myClass) {
/* Do stuff */
}
}
Any hints as to how this can be done? Thanks!
Class
has both an isInstance() method and an isAssignableFrom() method for checking stuff like that. The closest to what you're looking for is:
if (myClass.isInstance(obj)) {
Update: From your comment, you want to pass the name of a class into a method and check if something is assignable to that class. The only way to do that is to pass the class name as a String, then load the class and use one of the aforementioned methods. For instance (exception handling omitted):
private void methodName(String className) {
Class myClass = Class.forName(className);
Object obj;
/* Complicated code to find obj in datastructure */
if (myClass.isInstance(obj)) {
/* Do stuff */
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With