difference between calling method as static and as class method through reflection - java

I have a line of code like this:
ConfiguationManagerUtils.class.getResource(resourceName);
I don't understand why reflection is used here. What is the difference between calling it like a static class method:
ConfiguationManagerUtils.getResource(resourceName);

It's not using reflection at all. The getResource(String) method called in your first snippet simply isn't declared on ConfigurationManagerUtils - it's declared on the Class class, as an instance method. If the second code snippet works as well, that's because there's a static getResource(String) method declared in ConfigurationManagerUtils (or a superclass). That may well do something entirely different to Class.getResource().
The first snippet is just using a class literal (ConfigurationManagerUtils.class) to obtain a reference to a Class instance on which it can call the getResource(String) instance method.

In this code you call a non-static method of object Class referring to your ConfiguationManagerUtils class:
ConfiguationManagerUtils.class.getResource(resourceName);
In this code you call a static method of your ConfiguationManagerUtils class.
ConfiguationManagerUtils.getResource(resourceName);

This isn't using reflection, you're just accessing the class attribute of ConfiguationManagerUtils.

There is a BIG difference between the 2 calls.
ConfiguationManagerUtils.class.getResource(resourceName);
the method getResource() of the class-object of ConfiguationManagerUtils is called. Not the one you define inside the class ConfiguationManagerUtils.
ConfiguationManagerUtils.getResource(resourceName);
The methode from the class ConfiguationManagerUtils is called. i.e,
the method is defined in the code inside class
ConfiguationManagerUtils.

Related

How to call a singleton method from a Java POJO?

I wondered if it would be possible to call from a POJO a singleton bean's method through its interface. Maybe this idea is wrong or the architecture...but this is what I would like to accomplish if it is possible, because this is the architecture of the project.
I notice that when I call getInstance() (the method from the singleton's interface) from the POJO, there is an error occuring, telling me that the method has to be static, but if I make the method static, then I have to write the implementation in the interface and I can't get the singleton instance.
Your current approach with the interface is flawed. By default, all methods in an interface (up until Java 8) are static, and are implemented by instance methods in the implementing class.
This means, this is not an option. After all, you'll need to run the method to create an instance, meaning, you don't have an instance yet, so you have no instance to call it on.
Putting the same static method in an abstract class you extend, is also not a solution: a super class should never be aware of it's subclasses. If it is a static method (which it needs to be), you need to keep it in the class itself: a static method in an abstract class can (through an anonymous implementation of the abstract class) return an instance of the abstract class, but this is not the same as an instance of the subclass, which is what you are looking for.
In order to use this method for the subclass, you will need to inherit it from the super class. But, it will still return an instance of the super class. You'll need to overwrite the method in the subclass by the correct one, so the best solution is to add it straight in your Singleton class.
You are not allowed to have static methods in your interfaces (at least not until Java 8). Something like this is not allowed:
MyInterface var = new MyImplementingClass();
var.staticMethod();
Just remove the interface and do your static method call against the class where the static method resides.
Search a bit for the singleton pattern - the 'standard' way to do this involves classes and not interfaces, so rethink your design.
The idea seems to be wrong. A static method is always at a class level and hence you can never declare a method as static in a Java interface(you can do this in Java 8). However, this seems like the wrong design. If you really want to do something like this -
1)Make the Interface an abstract class.
2)Create a static method called getInstance();
3)Extend the abstract class in your POJO singleton class.
Hope this helps!!

Control access in methods

I have a question about Java.
I have a class Say.java that has some methods, like sayHello(), saySomething(), sayBye(), ...
I have other classes too. I have a class Person, and two subclasses of Person: Senior and Junior.
My job to do is the following:
I have to set the Say.java class to be private, and create a public class SayFactory.java, with a method called getInstance. Then, to create a new instance of the Say.java class, I have to call my getInstance method with one argument: an instance of either Senior.java or Junior.java. If I create an instance of Say.java using a Senior.java object, I must be able to access all of the methods of Say.java. But if I do the same thing with Junior.java, I should be able to access all of Say.java's methods EXCEPT saySomething().
Can someone please explain how to do this and how it works?
Apologies by the way - I'm from Spain so my English isn't that great. If you don't understand the question, let me know and I'll try to write it out more clearly.
First refer to this as answer to making a class private: Java: Why can we define a top level class as private?
For the objects that you want "private" you will have to make all the fields and possibly methods of it private (depending on what you need). Then as #user1071777 mentioned set up public getters and setters.
Some basic information on calling methods of an object:
http://docs.oracle.com/javase/tutorial/java/javaOO/usingobject.html
To create the connection between classes you can have a class have another class as part of its definition and set it up through constructor or public setter.
I know that I can't write Private Class but I can do a inner class.
I have a class SayFactory and within this I got another called Say
The SayFactory have a method called getInstance(), and in this method I create an object of Say class and return this object. The problem is, how to deny access to method saySomething() if the parameter of getInstance() is a object of Junior.

Working with Math class without instantiating it

I am new to programming and was studying "Head First Java", I just saw a problem where there was used Math class like this
int x= Math.round(float value);
and it was mentioned we don't need to instantiate Math class because its constructor is set private. What does that mean? Until now I read we need to instantiate that class and reference variable to play around with methods and instance variables of the class how does Math class work like this?
we don't need to instantiate Math class because its Constructor is set Private
Because all the methods in Math class are static you can use the class name to invoke them. So there is no use instantiating the class , hence the constructor was declared private. it will also prevent sub classing the Math class, since it is the only constructor.
Look at the open source code :
Don't let anyone instantiate this class.
private Math() {} // only constructor defined in Math class
The methods of Math class doesn't depend on the internal state of the class , they are just like utility functions . So it was wise to declare them as static. static methods can be invoked by directly using the classname , hence no use of instantiating the class. They belong to the class, not specific objects of that class.
You can refer the JLS 8.4.3.2 :
A class method is always invoked without reference to a particular object.
The Math class have all methods as a static, and you need to get the method from the class itself. No need to create instance variable to access Static variable and methods
Refer Math Class java doc. you find all method here static i,e. Math.round
Private constructors means that they can only be called upon from within the class to which they belong, a good example of the use of private constructors can be found here Can a constructor in Java be private?
Private constructors do however have nothing to do with the fact that you can use methods from the MATH class without instantiating them. This is because the methods of MATH class are static i.e. a static method can be called upon without instantiating an object of the class to which the methods belong.
As said in the comments above, you have no use of instantiating a MATH object, therefore the constructor is private, but you could use the MATH methods anyway had the constructor been public.

Java call method in Main class

Let's say I have Main class, and it has an instance of class A.
How can I call a method in Main class within class A ?
Thanks!
This is called Composition...Where a class has a Reference of other class...
Composition is preferred over Inheritance when we need one or few functionalities But Not all the functionalities of a class.
Eg:
public class A{
Main m = new M(); // m is a Object Reference Variable of type Main in class A
m.go(); // go() is a method in class Main
}
If it is an instance method, then you need an instance of M inside A to call M's method inside A. If it is a static method, you can just call it directly. But you're holding circular references so beware.
Main.methodName() for a static method.
Though it sounds to me like what you're trying to do may be bad practice. Your Main method or class should simply be an entry point
To call a method in Main class from calss A you need an instance of Main class within the class A(considering them in same package) if both the calsses have no relation like inheritance.if static then you may call Main.methodName();
If the method is a static method (i.e. was declared with "public static ReturnType methodName()") then in the A class, you need to call Main.methodName().
However, if the method is an instance method (declared as "public ReturnType methodName()") then you need to somehow pass an instance of Main into the instance of A (perhaps through the constructor, or a setter method). Inside the A class, you could then call instanceOfMain.methodName().
However (as some people have already mentioned) this is probably not the best way to handle things. The Main class should simply be where the program starts; it is not where you should be doing any real program logic.

How does this object get created?

Many articles say objects get created only after the class's constructor gets called. But I found this snippet and it works fine.
public class A {
public A(){
this.foo();//line #1
}
private void foo() {
System.out.print("without an instance..!!!!");
}
}
class B extends A
{
public static void main(String[] args){
A a = new A(); //line #2
}
}
Here you see, I'm trying to create an object of its super class in line #2 and in its constructor how come its method got called without an instance. What's going on here, is Constructer of instance of A is getting called here.?
The constructor is always called when an object is created. Even if you don't explicitly define a constructor, the compiler will generate one for you with an empty body.
You may call other methods of the class from the constructor. All non-static methods get an implicit (compiler generated) parameter to this, the actual class instance. However, it is important to know that while executing the constructor, the object is not yet fully created, although all data members of the class in question (if there are such) have already been initialized, at least to some default value. Because of this, you
should not publish this (i.e. pass it to other objects / threads) before exiting the constructor call, and
you should not call non-final, non-private methods from the constructor.
Doing either of these (in a non-final class) means that you give access to an object not yet fully constructed, which may result in subtle, hard to find bugs later. E.g. if the virtual method in question is overridden in a subclass and the implementation depends on some member defined and initialized only in the subclass constructor, the method gets called before the subclass member is correctly initialized, thus it won't have the value you would expect.
Because public static void main is the entry point of the programm. So you do not require to create instance of the class B.
The method signature for the main() method contains three modifiers:
* public indicates that the main() method can be called by any object.
* static indicates that the main() method is a class method.
* void indicates that the main() method has no return value.
Read more : Understanding public static void main function
So that Constructor of A is get called when the programm get executed and that it calls the foo method of the super class A.
It's not called without an instance.
You call it on this - that's an instance.
The constructor of A is getting called because you called it directly. However, if you wished to call A through B, within Main [which is called without a current instance of the containing class B (1 because its static, and 2. its reserved for the beginning of the application)] you would just change the "new A()" to "new B()"
Since you're using a constructor with no parameters, a default constructor in automatically generated at compile time.
Whether main() is the entry point or not is not the explanation. The reason is that main() is static, therefore doesn't require an instance of its class.
No instance of B is ever created by this program.
class A is public, and its inherited by class B. class B can instantiate class A, with
A object=new A()
and the object initialization is done by Constructor method defined automatically. Constructor of A in turn calls method foo(), which is private to class A. As far as i know, to call a method from a class which is in the same class scope, no instance is needed.

Categories

Resources