This question already has answers here:
Understanding Java's protected modifier
(6 answers)
Closed 7 years ago.
i cannot access a protected method in a subclass (in same package).
I am using spring-jms API's , DefaultMessageListenerContainer class.
In my code, i have an instance of DefaultMessageListenerContainer class, and i am trying to invoke getBeanName() method on that object, but in eclipse it says,
"The method getBeanName() from the type AbstractJmsListeningContainer is not visible"
As per javadoc ,this getBeanName() method is a protected method defined in superclass, 'AbstractJmsListeningContainer'.
Per my understanding, we should be able to access protected method inside subclass.
Am i missing something ?
Attaching a sample java code snippet.
The code fragment you posted is not accessing getBeanName() from within the subclass. It is trying to access it from client code. You'd have to define your own subclass to expose a public method to get to it:
class MyDefaultMessageListenerContainer extends DefaultMessageListenerContainer {
public getMyBeanName() { return getBeanName(); }
}
MyDefaultMessageListenerContainer container = new MyDefaultMessageListenerContainer();
String name = container.getMyBeanName();
Note that you can't simply override getBeanName() because it is declared final.
Related
This question already has answers here:
Cannot make a static reference to the non-static method
(8 answers)
Closed 6 years ago.
I have a JSP application with a plain java class of Login.java and a servlet with a call to a procedure named loginList in the doGet method. The loginList procedure needs to create a list of logins using a java class named OAVDbUtil with a method "getLoginsList". But Eclipse does not seem to recognise the "getLoginsList" procedure and when I enter it the massage of "eclipse cannot make a static reference to the non-static method" is given. But everything looks okay as I have not stated the getLoginsList as static. I think there is a way to create an instance of the OAVDbUtil to avoid having to create multiple instances of New OAVdbUtil objects but can someone tell me how to do this please and NOT get the message of "eclipse cannot make a static reference to the non-static method"?
Here is some code and a screen dump
Screen dump of servlet
Here is the code for the OAVDbUtil
public OAVDbUtil(DataSource theDataSource) {
dataSource = theDataSource;
}
public List<Login> getLoginsList() throws Exception {
List<Login> loginList = new ArrayList<Login>();
You need to provide an instance of OAVDbUtil to the servlet, and then call getLoginsList() on that object.
A servlet might construct such an object in its initialization method, or it could be injected into the servlet by a container.
getLoginsList() is not static, make it and it will work.
You are getting this error because getLoginsList() is not static.
You can change that method static
public static List<Login> getLoginsList() throws Exception {
(Or)
Create a object for OAVDbUtil
OAVDbUtil dbUtil = new OAVDbUtil();
List<Login> logins = dbUtil.getLoginsList();
OAVDbUtil.getLoginsList() is how you use a static method in a class, you can't use this to access an instance method of a class.
If you intended getLoginsList to be a static method then declare it as such:
public static List<Login> getLoginsList() throws Exception
If you want getLoginsList to be an instance method then you need to have an instance of the OAVDbUtil class and available and call the method using:
OAVDbUtil theInstance = .... get from somewhere
List<Login> logins = theInstance.getLoginsList();
This question already has answers here:
Retrieving parameter values through reflection
(2 answers)
Closed 9 years ago.
I'm trying to get some runtime information to do some debugging. Is there a way to access the parameters actually passed to a method?
I know the calling class and method, but not the parameters and their value at runtime. Any Ideas how to solve this? Thanks in advance.
My code so far:
//get the class I wanna know something about out of the call history
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
String callerMethod = stacktrace[2].getMethodName();
//load the class to get the information
Class<?> c = Class.forName(stacktrace[2].getClassName());
Method[] methods = c.getMethods();
Class<?>[] parameters = methods[1].getParameterTypes();
//get the parameter data
(parameters[y].isArray()? parameters[y].getComponentType() : parameters[y]).getName();
//TODO: how about the parameter value at runtime?
The code has to be generic for all Classes I will implement. Example of usage:
public class doClass() {
public void doSomething(Object o) {
//here comes my debug line
magicDebugger(level);
}
}
level is the switch/trigger to activate console/db/file/mail output or whatever of some information
I expect following output (maybe there's some System.out.println in the magicDebugger class):
[debug] caller: com.company.package.doClass.doSomething(Object o); value of o at runtime = java.lang.String "test"
you can use http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Proxy.html
Proxy class or AspectJ framework to do that
Look into using reflection for this. That should provide what you're looking for.
This question already has answers here:
Java Pass Method as Parameter
(17 answers)
Closed 9 years ago.
I am experienced in JavaScript but new to Java. I am trying to figure out how to pass a function as a parameter of another function. In JavaScript this would like the block in Figure 1.
Figure 1
function fetchData(url, callback) {
// Do ajax request and fetch data from possibly slow server
// When the request is done, call the callback function
callback(ajaxResponse);
}
Is there a similar way of doing this in Java? I have searched the internets, but found little that is helpful on a novice level.
Unfortunately, the only equivalent (that I know if) is defining an interface which your fetchData method will accept as a parameter, and instantiate an anonymous inner class using that interface. Or, the class calling the fetchData method can implement that interface itself and pass its own reference using this to method.
This is your method which accepts a "callback":
public void fetchData(String url, AjaxCompleteHandler callback){
// do stuff...
callback.handleAction(someData);
}
The definition of AjaxCompleteHandler
public interface AjaxCompleteHandler{
public void handleAction(String someData);
}
Anonymous inner class:
fetchData(targetUrl, new AjaxCompleteHandler(){
public void handleAction(String someData){
// do something with data
}
});
Or, if your class implements MyCoolInterface, you can simply call it like so:
fetchData(targetUrl, this);
This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 9 years ago.
I'm working on some JPA stuff and i'm a little confused with some of the start up code that you have to write.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("sample");
EntityManager manager = factory.createEntityManager();
EntityTransaction transaction = manager.getTransaction();
Those three variables all have an interface as their type. How can we do things like
manager.persist()
transaction.commit()
etc if interfaces cannot be instantiated?
Interface cannot be instantiated but an interface reference can hold an object of any class implementing that interface. So in your case
EntityManagerFactory factory
is a reference of interface which is holding an object of the class implenting it , returned by :
Persistence.createEntityManagerFactory("sample");
and hence this statement becomes correct:
EntityManagerFactory factory = Persistence.createEntityManagerFactory("sample");
You are correct. Interfaces can not be instantiated but they provide a contract to call methods on objects that implement the interfaces.
So when you for example take a look at the EntityManager, factory.createEntityManager() is returning an object that implements the interface EntityManager. Interfaces make sure that the returned object provides certain required methods.
I think you are misunderstand what happened here.
EntityManager manager = factory.createEntityManager(); // here manager is only a reference You are getting that from EntityManagerFactory.
Now Factory class returns the manager type object. There is no instantiating for interfaces in Java
I think this is better seen than expained.
Examples:
public class AttackCommand implements Command {}...
public class DefendCommand implements Command {}...
....
let's say we wanted to add these to a common list of commands. Then you could add these to the list below.
(in a new class)
public ArrayList<Command> commands = new ArrayList();
public CommandManager() {
commands.add(new AttackCommand());
commands.add(new DefendCommand());
}
Now here is where that supposed reference comes in. What if we wanted to get a list of the command by name (pretending command has a getName method), or the last attacked target via AttackCommand (pretending it has a LastAttacked method)?.
public void printNames() {
for (Command cmd : commands) {
System.out.println(cmd.getName());
}
}
public Entity getLastAttackTarget() {
for (Command cmd : commands) {
if (cmd instanceof AttackCommand) {
return cmd.lastAttacked();
}
}
}
(I know that a map of the commands to just grab by name would be better, but for the sake of the example....)
In essence, it's a better general reference to all things that inherit the interface, but not the interface itself.
My previous post was not very clear, sorry for that. I will try to give a better example of what I am trying to do.
I have an Java application that will load .class files and runs them in a special enviroment (the Java app has built-in functions) Note: This is not a library.
That Java application will then display an applet, and I want to modify the variables in the applet.
The main class of the applet is called 'client'.
The Java application will load the applet by creating an new instance of class 'client'.
I already got access to the 'client' class. the Java application will put the applet in a variable:
Applet client = (Applet) loadedClientClass.newInstance();
So I did this:
Class<?> class_client = client.getClass();
I can now read and set the fields but the 'client' class will call a funation of an other class, like this:
otherClass.someVoid(false);
And if I try something like:
class_client.getDeclaredMethod("otherClass.someVoid",boolean.class);
It will fail, saying that the function can not be found.
'otherClass' is the direct class name, it is not a reference to a new instance of the class as far as I know.
Is there any way to get 'otherClass.someVoid'?
You're using getDeclaredMethod like a static method (expecting it to return methods from any class), but it only returns method from the class itself. Here's how you can call otherClass.someVoid(false).
Class<?> otherClass = Class.forName("com.xyz.OtherClass"); // Get the class
Method method = otherClass.getDeclaredMethod("someVoid", boolean.class);
// If the method is an Class (ie static) method, invoke it on the Class:
method.invoke(otherClass, false);
// If the method is an instance (ie non-static) method, invoke it on an instance of the Class:
Object otherInstance = otherClass.newInstance(); // Get an instance of other class - this approach assumes there is a default constructor
method.invoke(otherInstance, false);
If the class isn't initialized, the var someInteger doesn't exist. It's a member variable, so it only exists inside of instances of the class. So, you can't change it since it's doesn't exist. Now, if you made it a static variable, then you could change it.
Is there any way to change 'otherClass.someInteger' through the
'mainClass' class?
No.
But you can get it via OtherClass' class via Class.forName:
Class<?> theOtherClazz = Class.forName("OtherClass");
And then get the methods via theOtherClazz.getDeclaredMethod