Dear friends I am beginner to exception handling in java. I got this sample from one tutorial and I run this code its printed Arithmetic exception. If I remove that method which is have parameter as ArithmeticException then the first method called that is print Exception.
Please any one can explain what is happening with this code.
public class Question1 {
public static void javaHungry(Exception e) {
System.out.println("Exception");
}
public static void javaHungry(ArithmeticException ae) {
System.out.println("ArithmeticException");
}
public static void javaHungry(Object obj) {
System.out.println("Object");
}
/**
* #param args
*/
public static void main(String[] args) {
javaHungry(null);
}
}
When you overload methods and passed a parameter which suits for all, the most specific methods can be choose at run time.
The order of specificiation here is
ArithmeticException > Exception > Object
1) If you remove method with ArithmeticException it chooses Exception.
2) If you remove method with Exception it chooses Object.
Related
Basically which one will execute first the main method or the constructor?
public class ConstructorExp {
public ConstructorExp() {
System.out.println("Ctt");
}
public static void main(String[] args) {
System.out.println("Inside Main Methos");
System.out.println("Main");
}
}
The main method will always be excecuted first, because it is a special static method that will be called from Java itself to start an application.
For more about the main method please read Java main() Method Explained for example.
Constructors will be created on object creation - in your case no object creation happens - so the constructor will never be executed.
You could modify your example to also execute the constructor:
public class ConstructorExp {
public ConstructorExp() {
System.out.println("Ctt");
}
public static void main(String[] args) {
System.out.println("Inside Main Methos");
ConstructorExp example = new ConstructorExp();
System.out.println("Main");
}
}
Be carefully, because the example object is never used the constructor call might be eliminated by some kind of optimization depending on the compiler you are using.
I am looking for an elegant way to create a factory for dependency injection. In my case, the factory simply has to call a one-argument constructor. I found this answer outlining how to use a Function<ParamType, ClassToNew> for such purposes.
But my problem is: in my case, my ctor declares to throw some checked exception.
What I don't get: creating that Function using a method reference to that constructor doesn't work. As in:
import java.util.function.Function;
public class Mcve {
public Mcve(String s) throws Exception {
// whatever
}
public static void main(String[] args) {
Function<String, Mcve> mcveFactory = Mcve::new;
}
}
tells me about "Unhandled exception: java.lang.Exception" for Mcve::new. Although this code is not invoking the constructor.
Two questions:
why that error? The above code does not invoke the ctor (yet)?
are there any elegant ways to solve this puzzle? ( simply adding throws Exception to my main() does not help )
You need to provide a custom interface ThrowingFunction which has one method that throws Exception.
public interface ThrowingFunction<ParameterType, ReturnType> {
ReturnType invoke(ParameterType p) throws Exception;
}
public class Mcve {
public Mcve(String s) throws Exception {
// whatever
}
public static void main(String[] args) {
ThrowingFunction<String, Mcve> mcveFactory = Mcve::new;
}
}
Using this approach results in calling mcveFactory.invoke("lalala"); forcing you to handle the exception thrown by the constructor.
Reason for the error is that the actual function reference you want to store (not 100% sure about the terminology) throws an exception and therefore the types simply do not match up. If you could store Mcve::new inside a function then whoever calls the function no longer knows an Exception can be thrown. What would then happen if the exception would actually be thrown? Both throwing the exception and discarding it do not work.
Alternative: if you need to actually retrieve a Function<String, Mcve> in the end then you need to write a function (or lambda) that invokes the constructor, catches the exception and either discards it or rethrows it wrapped inside a unchecked RuntimeException.
public class Mcve {
public Mcve(String s) throws Exception {
// whatever
}
public static void main(String[] args) {
Function<String, Mcve> mcveFactory = parameter -> {
try {
return new Mcve(parameter);
} catch (Exception e) {
throw new RuntimeException(e); // or ignore
}
};
}
}
I would argue that the error message itself is at least a bit misleading since you normally see it when actually invoking the method. I can certainly understand the confusion resulting in the first sub-question. It would be clearer (sadly not possible) to state something like
Incompatible types Function<String,Mcve> vs. Function<String,Mcve> throws Exception.
I had to do that just recently... If you can change the class definition, you could use the infamous sneaky throws way of doing things:
static class OneArg {
private final String some;
#SuppressWarnings("unchecked")
public <E extends Exception> OneArg(String some) throws E {
try {
this.some = some;
// something that might throw an Exception...
} catch (Exception e) {
throw (E) e;
}
}
public String getSome() {
return some;
}
}
Function<String, OneArg> mcveFactory = OneArg::new;
I've been thinking about this for a while and indeed - if you want to have a Function that declares clearly your intention, I think that you need to have a Function that would extend the java.util.Function, something like this:
#FunctionalInterface
public interface ThrowingFunction<T, R> extends Function<T, R> {
R applyWithExc(T t) throws Exception;
#Override
default R apply(T t) {
try {
return applyWithExc(t);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
You can btw choose which method you call when you define your constructor reference - the one that would throw an Exception and one that would silently wrap it with a RuntimeException.
This question already has answers here:
How do I find the caller of a method using stacktrace or reflection?
(13 answers)
Closed 7 years ago.
When I call on a method in a class, the method will get the java.lang.Class that called on it using sun.reflect.Reflection.getCallerClass(2). This is not what I want. I want the Reflection to return the class Object that called on it (i.e. if I call the method from the Bar class, the Reflection.getCallerClass() returns an object of type Bar)
Let's suppose I have this class:
public class Foo {
public static void printOutCallerObject() {
System.out.println(classTypeThatCalledOnMethod);
}
}
Called by:
public class Bar {
public static void main(String[] args) {
Foo.printOutCallerObject();
}
}
And then the program would print out "Bar".
Here's a quick demo of how you can get the calling class - you cannot get the calling object unless you pass it to the method because it is not on the stack.
public class ReflectDemo {
public static class Foo {
public static void printOutCallerObject() {
StackTraceElement[] trace = Thread.currentThread().getStackTrace();
// trace[0] is Thread.getStackTrace()
// trace[1] is Foo.printOutCallerObject()
// trace[2] is the caller of printOutCallerObject()
System.out.println(trace[2].getClassName());
}
}
public static class Bar {
public static void barMain() {
Foo.printOutCallerObject();
}
}
public static void main(String[] args) {
Foo.printOutCallerObject();
Bar.barMain();
}
}
This prints:
ReflectDemo
ReflectDemo$Bar
And Foo.printOutCallerObject(); will print out the class of whatever code calls it. The call to Thread.currentThread().getStackTrace() isn't cheap, so be aware that you may incur some runtime costs. This pattern is often used for logging, to record which piece of code triggered the logging call.
I have tracked down an error to line 362 of the java.lang.Class class:
Constructor<T> tmpConstructor = cachedConstructor;
The variable does not seem to get assigned. In the debug expression windows it only says "tmpConstructor cannot be resolved to a variable". The cachedConstructor is not null.
An error is only thrown further down when a the newInstance() function is called:
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
Context:
Using JSON Plugin with the Struts2 framework to create Java objects from the received JSON.
The field it is trying to parse is a subclass of an abstract class.
On further inspection (thanks to user902838) I was missing that it can't instantiate an abstract class. So I need to find out how it can instantiate subclasses, which is a different question.
Can someone please explain to me why the tmpconstructor is empty?
It's hard to tell without any information about the class you're trying to instantiate or the exception/error you observe, but my best guess would be that the class does not have a nullary constructor. This program exhibits such a problem:
package example;
public class NewInstanceTest {
public NewInstanceTest(String s) {
}
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
The problem can be fixed by adding a nullary constructor:
package example;
public class NewInstanceTest {
/* nullary constructor: */
public NewInstanceTest() {
this("default");
}
public NewInstanceTest(String s) {
}
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
or by removing all non-nullary constructors so that Java will provide a nullary one automatically:
package example;
public class NewInstanceTest {
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
Please see this Java Class
class Demo
{
public static void a(String s)
{
System.out.println("string called");
}
public static void a(Object a)
{
System.out.println("Object called");
}
public static void main(String...asrgs)
{
a(null);
}
}
The output of this code is "string called" but I am not able to understand that how compiler is able to resolve between Object and String.
Moreover, examine this code fragment
class Demo
{
public static void a(String s)
{
System.out.println("string called");
}
public static void a(Integer n)
{
System.out.println("number called");
}
public static void a(Object a)
{
System.out.println("Object called");
}
public static void main(String...asrgs)
{
a(null);
}
}
Here we get a compile time error related to ambiguous call (which is quite obvious).
Any good explanations for this ?
The answer lies in §15.12.2 of the JLS:
The second step searches the type determined in the previous step for member methods. This step uses the name of the method and the argument expressions to locate methods that are both accessible and applicable, that is, declarations that can be correctly invoked on the given arguments.
There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is the one used at run time to perform the method dispatch.
(my emphasis)
...and §15.12.2.5, which the section above refers to, which has the full details of specificity rules, but also this handy summary:
The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time error.
In your first example, a(String) is more specific than a(Object), so the compiler knows which one to use and is happy. In your second example, both a(String) and a(Integer) are more specific than a(Object), but either is applicable to null and they're in separate lineages (String is String > Object, Integer is Integer > Number > Object), creating the ambiguity the compiler complains about.
If they were in the same lineage, there'd be no ambiguity, because there'd be a single applicable most specific option. For example:
class Base {
}
class Child extends Base {
}
class GrandChild extends Child {
}
public class Example {
public static final void main(String[] args) {
a(null);
}
public static void a(Base b) {
System.out.println("Base");
}
public static void a(Child b) {
System.out.println("Child");
}
public static void a(GrandChild b) {
System.out.println("GrandChild");
}
}
That prints "GrandChild", because while both a(Child) and a(GrandChild) are more specific than a(Object), a(GrandChild) is more specific than a(Child).