Android studio is not creating object using another class - java

WeatherDataModel weatherDataModel = new WeatherDataModel.fromJson(response);
I am creating a WeatherDataModel(my second class) object using the method fromJson ( defined in WeatherDataModel class) in my MainActivity using the parameters response.
But when I write above code Android studio can't recognize fromJson, but when I write this:
WeatherDataModel weatherDataModel = new WeatherDataModel();
weatherDataModel.fromJson(response);
It doesn't show any error.
Is there's a difference between these 2 lines?

You need an instance of an object before call a method,
so you code should be like this.
WeatherDataModel weatherDataModel = new WeatherDataModel().fromJson(response);

Either you missed the brackets for the constructor or you can even get rid of the new keyword by declaring the fromJson method static, which would make even more sense from a point of readability of the code.
If fromJson is not static, it can be called on a living instance at any time, destroying any values already stored in that instance.
So I'd declare that method as
public static WeatherDataModel fromJson(String response) {
WeatherDataModel wd = new WeatherDataModel();
// parse your response into wd's fields
return wd;
}
and from outside your call then looks like
WeatherDataModel model = WeatherDataModel.fromJson(response);
Hope this helps, cheers

Related

How to create one instance of a class available to entire servlet [duplicate]

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();

I don't understand the call to the parent class from within the class in this JAVA class

Can you help me understand why we call the parent class here? I found a download class that seemed simple enough but could use help wrapping my brain around the first method.
public class DownloadHandler {
public static void main(String[] args) throws Exception {
DownloadHandler d = new DownloadHandler();
d.URLSetUp(args[0]);
}
....
}
I am trying to instantiate the handler in a for loop and getting an error.
DownloadHandler file = new DownloadHandler("http://example.com/"+cleanLink+"/"+filename+".pdf")
It says "DownloadHandler() in DownloadHandler cannot be applied to (java.lang.String)"
Your DownloadHandler class has a static void main method, which is the single point of entry when executing command-line programs.
That method is not a constructor.
What it does is initialize a new instance of DownloadHandler and invoking an instance method on that object by passing the given String argument.
Not sure what's the usage there.
In order for your initialization to compile, you probably want to add a constructor that performs similar operations, given a single String parameter in your case.
For instance:
public DownloadHandler(String s) {
URLSetUp(s);
}
Java adds a default constructor to every class that doesn't provide one. A constructor is a method without a return type. So, in your case the default constructor DownloadHandler() is automatically added to your class and it does not take any parameters while you are trying to initialize it with a String.
The String you are using in main method right now is coming from console from user.
From your code its obvious that you want to pass a argument via command line parameter. But when you are initiating DownloadHandler, you are passing that string here which is not you should be doing.
There are two things you can do now.
Pass the string via command line parameter
java DownloadHandler yourstring
Write a constructor which accepts the string. In your code outside of your main method
String url;
public DownloadHandler(String str)
{
url = str;
}
Now call
d.URLSetup(url);
Hope this will clear your doubts.

Java Reflection with Object... as a parameter

I'm wanting to use Java reflection to call a method on a class of mine that has the following signature:
public Object execute(Object...params)
In my loader class, I have the class loaded, but I'm not sure how to setup my getMethod call. Currently, I have something like this:
Method classEntry = _loadedClass.getMethod("execute", new Class[]{Object[].class});
I then try to invoke this method after creating a newInstance of my class by calling:
Object classObj = _loadedClass.newInstance();
classEntry.invoke(classObj, params); // params comes in from the method as Object...params
This is giving me a java.lang.NoSuchMethodException Exception. I know that my issue lies in my getMethod call. How should I set that up to accept a params object?
If params is of type Object [] then you need to call invoke like this:
classEntry.invoke(classObj, new Object [] {params});
But this does not explain NoSuchMethodException

Java Reflection - Object is not an instance of declaring class

This question is being asked everywhere on Google but I'm still having trouble with it. Here is what I'm trying to do. So like my title states, I'm getting an 'object is not an instance of declaring class' error. Any ideas? Thanks!
Main.java
Class<?> base = Class.forName("server.functions.TestFunction");
Method serverMethod = base.getMethod("execute", HashMap.class);
serverMethod.invoke(base, new HashMap<String, String>());
TestFunction.java
package server.functions;
import java.util.HashMap;
import java.util.Map;
import server.*;
public class TestFunction extends ServerBase {
public String execute(HashMap<String, String> params)
{
return "Test function successfully called";
}
}
You're invoking the method with the class, but you need an instance of it. Try this:
serverMethod.invoke(base.newInstance(), new HashMap<String, String>());
You are trying to invoke the execute method on the object base, which is actually a Class object returned by your Class.forName() call.
This would work for a static (class) method - but execute is a non-static (instance) method.
(It would also work for calling an instance method of an object of type Class - but that's not what you are trying to achieve here!)
You need an actual instance of TestFunction to invoke the method on, or you need to make the method static.
When invoking a static method by reflection, the first argument to invoke() is ignored, so it is conventional to set it to null, which clarifies the fact that there's no instance involved.
Although your current example method would do the same thing for any TestFunction object, in general an instance method could produce a different result for each object - so the .invoke() reflection method needs to know which object to run the method on.

Getting method via reflection

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

Categories