I'm new to Java with a decent background in python. I'm looking for a magic sauce in Java which is equivalent to isinstance() in python. I know we can do something like
if (cls.isInstance(obj)){ ... }
But I don't even know which cls it would be so I need something to tell me what instance is obj is. I can't check for hundreds of classes.
Thank you in advance.
EDIT:
I'm dealing with some exception which is wrapped in few other custom exceptions. My primary goal was to catch the exception for which I need to know what instance it is.
Exceptions have inheritance too. That means you don't have to know its exact class to catch it.
So if you want to catch every exception, you do
try {
// the code that throws the exception
} catch (Exception e) {
// handling the exception
}
If you are really desparate you can replace the Exception above with Throwable, to catch even more stuff, but in most cases, that would be a bad idea.
you can check the class instance by instanceof keyword in java. It returns true or false.
MyClass obj = new MyClass();
if(obj instanceof MyClass) {
//Do what you want
}
If you want to check exceptions which exception it is then in java every Exception is child of Exception class. you will check for any number of classes in which exception may be wrapped. at the end you will catch in Exception type. Now every exception will be catch.
try{
} catch(CustommException1 e) {
} catch(CustomException2 e) {
} catch(Exception e) {
}
You can get the full name of the class of obj by using
obj.getClass().getName()
If you don't like package names, you can also do
obj.getClass().getSimpleName()
Try instanceof operator...
for example:
` class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(s instanceof Simple1);//true
}
} `
There is no way to get a specific custom class by using instanceof or .getClass() in an Object. It would give you a type of LinkedHashMap.
To know the specific instance of the Object, the only way is checking its Keys, or trying to cast it.
There isn't a "magic sauce" that gives you what type of a custom class is an Object.
Related
So, I want to write these kind of things for my code, but there's too much code for one variable. How can I use modern Java for solving this problem shorter or cleaner? Moving it in the separate method doesn't solve the problem, because I still need to check the variable for null, which is wordy and adds extra method that used only once. It is possible to use Optionals here? Seems like return prevents this. Maybe there's the way for collapsing this thing into one for many variables like the foo described below? I don't know, just something to make it more readable and clean.
Foo foo;
try {
foo = FooProvider.getFoo(...);
} catch (FooProvidingException e) {
System.err.println("Foo exception: " + e.getMessage());
return;
}
// use foo, maybe in another method (when foo is the field).
I know, this question may be opinionated, but any help would be a valid answer.
Sorry for my poor english and thanks in advance!
What you're asking is not very clear, so I don't know at which extent my answer will be meaningful.
If I understand well, you have fields of any type (Foo, Bar...) and you would like to instantiate them using whatever kind of provider you wish, which can throw an exception while providing.
So at first, I don't think that you should return if an exception is thrown by the provider, but rather re-throw it or handle it. Because if you had an exception while getting your Foo and so you actually don't have a Foo, why would you continue (or why wouldn't you try to handle it somehow)?
Now this said and assuming that re-throwing/handling is taken care of, then I would define a ThrowingSupplier functional interface:
#FunctionalInterface
public interface ThrowingSupplier<T, E extends Exception> {
T get() throws E;
}
... and then I would create a static method like this:
public static <T, E extends Exception> T provide(ThrowingSupplier<T, E> supplier) {
try {
return supplier.get();
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
throw (E) e;
}
}
So at that point, I would be simply calling this utility method every time that I want to execute such kind of operation:
Foo foo = provide(() -> FooProvider.getFoo(...)); //either creates a Foo, or prints and re-throw a FooProvidingException
Bar bar = provide(() -> BarProvider.getBar(...)); //either createa a Bar, or prints and re-throw a BarProvidingException
Integer myInt = provide(() -> 3);
String myStr = provide(() -> "hello");
//... and so on
But of course, at least once you'll have to extract the logic. Then it's all about extracting it in a way that it becomes generic and doesn't need to be repeated for each distinct type of object.
I am also not sure what the end-goal here is but, as I understand it, here's a simpler version of achieving the following:
Declaring and initializing the variable(s)
Fetching values for it with a service provider
Handling any exceptions thrown by this (or if the value is null) and exiting method
Continuing execution if everything is as expected
public static void main(String[] args) {
Foo foo1, foo2, foo3, foo4;
try {
foo1 = Optional.ofNullable(FooProvider.getFoo()).orElseThrow(new FooProviderException(1));
foo2 = Optional.ofNullable(FooProvider.getFoo()).orElseThrow(new FooProviderException(2));
foo3 = Optional.ofNullable(FooProvider.getFoo()).orElseThrow(new FooProviderException(3));
foo4 = Optional.ofNullable(FooProvider.getFoo()).orElseThrow(new FooProviderException(4));
// this works in or out of try/catch block
foo1.printName();
foo2.printName();
foo3.printName();
foo4.printName();
} catch (FooProviderException fpe) {
System.out.println("Exception: " + fpe);
return;
}
// this works in or out of try/catch block
foo1.printAgain();
foo2.printAgain();
foo3.printAgain();
foo4.printAgain();
}
Recently I saw following piece of code on GitHub:
private static String safeToString(Object obj) {
if (obj == null) return null;
try {
return obj.toString();
} catch (Throwable t) {
return "Error occured";
}
}
I've never placed toString() method invocations inside the try-catch blocks. But now when I think about it, it might make sense. For example someone could overwrite toString() method in it's class that might throw a runtime exception, like NullPointerException. So we can try to catch Exception. But why Throwable? Do you think it makes any sense?
There is almost never a good reason to do this. The contract of toString() does not say it’s permissible to throw an exception from that method. Any code which throws an exception is broken code, and such an exception needs to be exposed and fixed, not suppressed.
In the case where you are converting some “bad” object from a library which is out of your control to a String, it might be appropriate to write catch (RuntimeExcepton e), but such a catch should be accompanied by comments which describe in detail why it is necessary, because under normal circumstances, it is not needed.
Rogue exception-throwing toString methods aside, note that Java already has at least two “safe” ways to convert a possibly null value to a String:
Objects.toString(obj, null)
String.valueOf(obj)
…so I would question whether the safeToString method should exist at all.
There are rare cases where you might want to catch an Error like this. In general it's a bad idea however, in this case it might make sense as this is generally for logging/debugging purposes and not used directly by the application.
I would prefer something more informative such as
private static String safeToString(Object obj) {
if (obj == null) return null;
try {
return obj.toString();
} catch (Throwable t) {
return obj.getClass() + ".toString() threw " + t;
}
}
e.g.
class Element {
Object data;
Element e;
public String toString() {
return data + (e == null ? "" : e.toString());
}
}
Element e = new Element();
e.data = "hi";
e.e = e; // oops
System.out.println("e: " + safeToString(e)); // doesn't kill the thread or JVM.
Throwable is the parent class of Exception and Error.
It is normally a bad idea to try and catch Error, as it is designed to not be caught.
Catching Throwable is just the overachieved and counterproductive version of catching Exception. Nonetheless, if for some reason you created another kind of Throwable you want to catch along with an Exception, that could be a way to do that in a single try/catch block. Not that it would be a clean way to do so, but it would work.
EDIT for the TL;DR : in most cases, catch Exception instead of Throwable.
It is incorrect to catch any Throwable and then continue execution since it includes Error, which is meant to be fatal:
From the Javadocs:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. The ThreadDeath error, though a "normal" condition, is also a subclass of Error because most applications should not try to catch it.
That is, some Errors can be recovered (e.g. LinkageError), but others not so much.
But catching Exception might be a valid use-case for example in logging code where you don't want the execution to break simply because a call to toString() fails:
private static String safeToString(Object obj) {
try {
return obj == null ? "null" : obj.toString();
} catch (Exception e) {
return "<exception: " + e + ">";
}
}
So I have the following bit of code:
public static Image getImage(String filepath, Class cl) {
try {
return ImageIO.read(cl.getResource(filepath));
}
catch (IOException e) {
e.printStackTrace();
}
return null; // Will never execute
}
It's a basic try-catch block. If I am unable to read the image and return it, I immediately go into my catch block. However, because my return is within the scope of the try block and not the entire function, my compiler issues an error when I try to compile and run because it sees that it's possible that I never hit a return statement. Therefore, I've added the return null; line to suppress this warning, but I'd rather have a neater way of doing this without putting code that will never run. I've tried adding
#SuppressWarnings("all")
To my code, but it still gives me an error. Any ideas? I feel like there should be a way to tell the compiler to ignore errors like this.
Also, if it is of any use, I am using IntelliJ as my IDE.
I would suggest what #LuCio eagerly in the comments tried to say. Just don't catch the Exception and pass it upwards:
public static Image getImage(String filePath, Class<?> clazz) throws IOException {
return ImageIO.read(clazz.getResource(filePath));
}
That way you have created an easy helper method. If you would return null, you'd have to document that in JavaDoc and every caller will have to use a not-null assertion logic to then throw an error if it is null.
A try catch block does the same. So instead of passing null upwards you just propagate the exception upwards. You somewhere said that you want to assign the Image to a static field, so you can do that easily like this:
static {
try {
MY_IMAGE = getImage("somepath", MyClass.class);
} catch(IOException e){
throw new IOError(e); // will kill the Vm with an error
}
}
But maybe somewhere you have another action. Than to just kill the VM. Maybe use a default image:
final Image image;
try {
image = getImage("somepath", MyClass.class);
} catch(IOException e){
e.printStacktrace();
image = new SomeDefaultImage();
}
// do something with image
Which all in all is the way to go. You can't have a helper method to decide what to do when it fails. That should always be done by the calling code.
Ok so, I believe I was confusing the purpose of the catch block. Thank you to #Ben and #Zephyr and everybody else for your help. I will be amending my code to:
public static Image getImage(String filepath, Class cl) {
try {
return ImageIO.read(cl.getResource("hello"));
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
throw new IOError(e);
}
}
Edit: After some more discussions, and looking through other options other people have posted, I have updated my code above, which satisfies the compiler. Note that replacing the line
throw new IOError(e)
with
System.exit(0);
does not fix the error because, as far as I know, the compiler cannot tell at compile time whether the program would end. It would've been helpful to have a way of suppressing the warning, since we know that at runtime the program will always (or practically always) end, but alas #SuppressWarnings is of no use.
I have several functions where I am casting an object to an explicit type.
The problem is, when this object is created, the type may not match the type I am casting to. Somewhere along the line there are some conversions that take place. However, it is possible the code never reaches these conversions. The fact that it doesn't is not an issue.
So when the code reaches the point where the casting will occur, all I need to do is put the part into a try catch block. In fact I don't even need to handle the exception in any special way.
But I have a lot of these functions. I would like to know if there is some way to wrap lines of code with a try catch block without actually writing out the try catch block. If I can call some function some how that will do it automatically.
try
{
// cast something
}
catch( ClassCastException e )
{
}
Instead I want to call a method that will put the try catch block around // cast something. Is there any way to do something like this?
Note: I don't do anything when I catch the ClassCastException. It is okay if I can't cast the object correctly, but I need to catch the exception so the code execution won't jump to some other place.
You can write a method like this to do the casting for you while ignoring any ClassCastException.
public static <I, O> O cast(I input, Class<O> outClass) {
try {
return outClass.cast(input);
} catch (ClassCastException e) {
return null;
}
}
You can use it like this:
Number n = new Integer(1);
Integer i = cast(n, Integer.class);
But you can also improve the code to avoid exceptions:
public static <I, O> O cast(I input, Class<O> outClass) {
if(outClass.isAssignableFrom(input.getClass())) {
return outClass.cast(input);
} else {
return null;
}
}
Not really, because this doesn't make any sense. If there's nothing you need to do when you catch the exception, then don't call the operation at all and delete all the code after. If it doesn't matter whether the operation succeeds or fails then don't call it in the first place.
More seriously - ahem, that was serious - you can not catch the exception and let the caller deal with it.
Try to create a common method that does this casting for you
private MyTypeOfObject cast (Object obj) {
try {
// your casting code
return newObj;
} catch (ClassCastException ee) {
// log and ignore
return null; // ????
}
}
There's nothing that I know of to do this (other than what #Scary_Wombat said) but if I were in your shoes I would just write a simple code generator to handle these repetitive/boilerplate cases using some templating engine like Freemarker or something more advanced like Antlr. There are tutorials about the place on each.
Which one will be better: ErrorCode or Exception for that situation?
I have ever been seeing these two error handling techniques. I don't know the disadvantages and advantages for each technique.
public void doOperation(Data data) throws MyException {
try {
// do DB operation
} catch (SQLException e) {
/* It can be ChildRecordFoundException, ParentRecordNotFoundException
* NullValueFoundException, DuplicateException, etc..
*/
throw translateException(e);
}
}
or
public void doOperation(Data data) throws MyException {
try {
// do DB operation
} catch (SQLException e) {
/* It can be "CHILD_RECORD_FOUND, "PARENT_RECORD_NOT_FOUND"
* "NULL_VALUE_FOUND", "DUPLICATE_VALUE_FOUND", etc..
*/
String errorCode = getErrorCode(e);
MyException exc = new MyException();
exc.setErrorCode(errorCode);
throw exc;
}
}
For second method, the error code retrieve form configuration file. We can add Error Code based on the SQL Vender Code.
SQL_ERROR_CODE.properties
#MySQL Database
1062=DUPLICATE_KEY_FOUND
1216=CHILD_RECORD_FOUND
1217=PARENT_RECORD_NOT_FOUND
1048=NULL_VALUE_FOUND
1205=RECORD_HAS_BEEN_LOCKED
Caller client for method 1
try {
} catch(MyException e) {
if(e instanceof ChildRecordFoundException) {
showMessage(...);
} else if(e instanceof ParentRecordNotFoundException) {
showMessage(...);
} else if(e instanceof NullValueFoundException) {
showMessage(...);
} else if(e instanceof DuplicateException) {
showMessage(...);
}
}
Caller client for method 2
try {
} catch(MyException e) {
if(e.getErrorCode().equals("CHILD_RECORD_FOUND")) {
showMessage(...);
} else if(e.getErrorCode().equals("PARENT_RECORD_NOT_FOUND") {
showMessage(...);
} else if(e.getErrorCode().equals("NULL_VALUE_FOUND") {
showMessage(...);
} else if(e.getErrorCode().equals("DUPLICATE_VALUE_FOUND") {
showMessage(...);
}
}
I recommend using Spring's JDBCTemplate. It will translate most existing databases' exceptions into unchecked exceptions that are specific, e.g. DataIntegrityViolationException. It will also include the original SQL error in the message.
Strange question, since both approaches do the same thing: they transform a checked SqlException in a different exception which seems to be unchecked. So the first one is the better one because it moves this into a single method.
Both leave some questions to be asked:
Isn't there some infrastructure that can do this conversion (Spring Template was mentioned in another answer)
Do you really want checked Exceptions, in my mind they are hardly ever worth the trouble.
Who is doing the real handling of the exception, does it get all the information needed? I would normaly expect some additional information about the transaction that failed inside of MyException, like: What did we try to do? (e.g. update a busines object); On what kind of object? (e.g. a Person); How can we/the user Identify the object (e.g. person.id + person.lastname + person.firstname). You will need this kind of information if you want to produce log/error message that tell you or your user more than 'Oops, something is wrong'
Why is MyException mutable (at least in the 2nd example)
A better design than either one would be to make your custom exceptions unchecked by extending RuntimeException.
I'd want your exception to wrap the first one, so coding it this way would be better, too:
MyException exception = new MyException(e); // wrap it.
If you do that, the second one is preferred. More information is better.
IMHO, it depends as how tightly your code is coupled with SQL.
If the method is to always (*1) be coupled with SQL, I would just declare and rethrow the SQLException (after cleanup / closing resources). Upper methods that are SQL-aware would then process it as they see fit (perhaps they need all the detail, perhaps they not).
If sometime in the future you could change the method for another which does not use SQL, then I would go for the second option.
(1): Be extra pessimistic with this assumption: "I think we are not going to change" should be interpreted as "Probably we will want to change". "We are not going to change" means "We cannot change without breaking lots of other methods anyway".
One differnce would the way you will catch the exception. In the first cases you can just catch the exception and you know what the error is. In the second case you have to catch the exception and check the code to see what the error is.