This question already has answers here:
newInstance() with inner classes
(3 answers)
Closed 5 years ago.
Look at following code:
public class Outer {
public static void main(String[] args) throws Exception {
new Outer().greetWorld();
}
private void greetWorld() throws Exception {
System.out.println(Inner.class.newInstance());
}
public class Inner {
public Inner () {}
public String toString(){
return "HelloWorld";
}
}
}
Why is it thrown java.lang.InstantiationException ?
After all, nested class Inner has nully constructor. Can someone explain it?
The [implicit] first argument in an inner's class' constructor is a reference to its enclosing class. When calling it via reflection, you need to explicitly provide it:
private void greetWorld() throws Exception {
System.out.println(Inner.class.getConstructors()[0].newInstance(this));
}
Your class Inner needs to be instantiated, one solution would be to declare it static.
static class Inner {
public Inner () {}
public String toString(){
return "HelloWorld";
}
}
Related
This question already has answers here:
Call a method of subclass in Java
(7 answers)
Closed 2 years ago.
Have a below code snippet.
public class Character {
private static String type;
public void doMainSomething() {
System.out.println("Doing Main Something");
}
public static class Gorgon extends Character implements Monster {
public int level;
#Override
public int getLevel() { return level; }
public Gorgon() {
Character.type = "Gorgon";
}
public void doSomething() {
System.out.println("Doing Something");
}
}
public static void main(String[] args) {
Character.Gorgon gor = new Character.Gorgon();
Monster mon = new Character.Gorgon();
mon.doSomething(); -> Error
}
}
How can I access inner class's Gorgon method doSomething using mon ? Is there any specific way, so that we could access class's method using Interface's ref type ?
Proper way is to declare the doSomething() method on Monster interface. If a method needs to be called on interface type, then that method needs to be on the interface or it's parent.
If that is not doable, then you can safely cast the mon to Character.Gorgon
if (mon instanceof Character.Gorgon) {
((Character.Gorgon) mon).doSomething();
}
This question already has answers here:
How are Anonymous inner classes used in Java?
(18 answers)
Closed 3 years ago.
I am trying to understand Supplier interface. I understand that it can return an object if we invoke its get() method. However, in the following example:
public class SupplierExample {
public static void main(String[] args) {
Supplier<String> s = new Supplier<String>() {
public String get() {
return "test";
}
};
System.out.println(s.get());
}
}
I am not able to understand how we can instantiate an object (s in above exaple) from an interface. Please advise.
This snippet contains an anonymous class instance, which implements the Supplier<String> interface.
It implements the only method of that interface with:
public String get() {
return "test";
}
which returns the String "test".
Therefore, s.get() returns the String "test".
This question already has answers here:
What is the reason behind "non-static method cannot be referenced from a static context"? [duplicate]
(13 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 4 years ago.
The method calls at the end of the main method are giving me an error saying "non-static method cannot be referenced from a static context" I'm not sure what I'm doing wrong in the method call.
public static void main(String[] args)
{
ArrayList<Candidate> voteCount = new ArrayList<Candidate>();
//add objects to voteCount
printListResults(voteCount);
totalListVotes(voteCount);
printListTable(voteCount);
}
public void printListResults(ArrayList<Candidate> election)
{
//some code
}
public int totalListVotes(ArrayList<Candidate> election)
{
//some code
}
public void printListTable(ArrayList<Candidate> election)
{
//some code
}
You simply need to declare these methods as static
public static void printListResults(ArrayList<Candidate> election) {
//some code
}
public static int totalListVotes(ArrayList<Candidate> election) {
//some code
}
public static void printListTable(ArrayList<Candidate> election) {
//some code
}
An alternative approach would be to instantiate an object of your class, as pointed out in the answer from JoschJava. Either way will work. Which approach you choose is partly a matter of taste and partly depends upon the needs of your application (which is beyond the scope of this question).
The problem is that you're trying to call a class method from a static method. You need to instantiate your class:
YourClass classObj = new YourClass();
classObj.printListResults(voteCount);
This question already has answers here:
What's wrong with overridable method calls in constructors?
(8 answers)
Closed 6 years ago.
I have the following code: The constructor of class A calls an abstract method implemented by class B which returns a variable from class B. This variable will be null by the time A calls the abstract method even if I instantiated it in the declaration. Is there any way I can instantiate it this way?
public abstract class A {
public A() {
isStringNull();
}
protected abstract String getMyString();
private void isStringNull () {
if (getMyString() == null) {
System.out.println("String is null :(");
} else {
System.out.println(getMyString());
}
}
}
public class B extends A {
private String amINull = "Of course not";
#Override
protected String getMyString() {
return amINull;
}
}
public static void main(String[] args) {
new B();
}
Can somebody please explain why the string will be null?
There is a detailed explanation of the order of initialization here:
Java order of Initialization and Instantiation
Basically, if you call a superclass constructor (explicitly or implicitly by inheritance and having an argumentless constructor), all of its initialization is done before it comes back to the subclass. So, in this case, the order is:
perform class A variable initializers
perform class A constructor body
return to class B constructor
perform class B variable initializers
perform class B constructor body
This is happening because you are first checking is string null and then you are assigning its value. When you extend some class, that class code will be executed at first!
Your compiler is doing it this way:
new B() -> isStringNull() -> private String amINull = "Of course not";
Check this modified code and see what will happen and look at execution steps
public abstract class A {
public A() {
System.out.println("Class A() called");
isStringNull();
}
protected abstract String getMyString();
private void isStringNull () {
if (getMyString() == null) {
System.out.println("String is null :(");
} else {
System.out.println(getMyString());
}
}
}
public class B extends A {
System.out.println("Class B() called");
private String amINull = "Of course not";
#Override
protected String getMyString() {
return amINull;
}
}
public static void main(String[] args) {
new B();
}
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.