I am confused of calling a private method by another method(public) belonging to the same class.Once I have been told I gotta create an object of that class and then call the private method via this object but in one of my questions in this forum I have been told that I dont need to use object.
public class Train() {
private void method1{......method definition..... }
public void method2{......how to invoke method1??}
}
Can I simply call the first method inside the second method by using method1(); or should I invoke it by creating an object of the class and Object_of_Train.method1();.
Which one should I use?
Within the class you should be able to call method1();
Outside the class you will need to call it from an instance of that class and will have access to public methods only
Use this.method1(); to call from method2() or any other non-static method in the class.
You can access the private methods of a class using java reflection package.
**Step1 − Instantiate the Method class of the java.lang.reflect package by passing the method name of the method which is declared private.
Step2 − Set the method accessible by passing value true to the setAccessible() method.
Step3 − Finally, invoke the method using the invoke() method.**
Example
import java.lang.reflect.Method;
public class DemoTest {
private void sampleMethod() {
System.out.println("hello");
}
}
public class SampleTest {
public static void main(String args[]) throws Exception {
Class c = Class.forName("DemoTest");
Object obj = c.newInstance();
Method method = c.getDeclaredMethod("sampleMethod", null);
method.setAccessible(true);
method.invoke(obj, null);
}
}
Source : Tutorialpoint
Related
I cannot invoke method in HazelcastSession class. I've obtained object and would like to add attribute via public method. I got this error.
I'm using Kotlin.
How to solve this?
The same attempt in Java
This https://github.com/spring-projects/spring-session/blob/master/spring-session-hazelcast/src/main/java/org/springframework/session/hazelcast/HazelcastSessionRepository.java#L321 is the definition of HazelcastSessionRepository's inner class HazelcastSession
The definition is basically
public class HazelcastSessionRepository {
final class HazelcastSession {
public void setAttribute(String attributeName, Object attributeValue) {
The inner class (HazelcastSession) isn't visible so you can't access what is inside.
I want to know if reference to an instance method of an arbitrary object of a particular type is serializable or not?
Example:
public class MyClass {
public void foo() {
System.out.println("Serializable");
}
}
SerializableConsumer
#FunctionalInterface
public interface SerializableConsumer<T> extends Consumer<T>, Serializable {
}
and field is:
SerializableConsumer<MyClass> serializableMethod = MyClass::foo;
EDITED
Assuming that SerializableFunction refers to a type that extends Serializable, the method reference will be serializable. There is nothing special about the particular type of method reference your are asking for.
Most notably, the “reference to an instance method of an arbitrary object” is not capturing any instance of MyClass, hence, the fact that MyClass isn’t Serializable is not important. It would be different if you were referring to an instance method of a particular instance like object::foo, as in that case, the object had to be serialized as well, which will fail at runtime, if its class doesn’t implement Serializable.
What will not work, is to refer to a void method as a Function of return type Void. I don’t know how your SerializableFunction<MyClass, Void> is defined, but if it is equivalent to Function<MyClass, Void>&Serializable, it will not work.
When you have an appropriate functional interface, serializing the method reference is no problem:
import java.io.*;
import java.util.function.Consumer;
public class MyClass {
public void foo() {
System.out.println("Serializable");
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Consumer<MyClass> consumer = (Consumer<MyClass>&Serializable)MyClass::foo;
byte[] serialized;
try(ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(consumer);
oos.flush();
serialized=baos.toByteArray();
}
Consumer<MyClass> deserialized;
try(ByteArrayInputStream bais=new ByteArrayInputStream(serialized);
ObjectInputStream ois=new ObjectInputStream(bais)) {
deserialized = (Consumer<MyClass>)ois.readObject();
}
deserialized.accept(new MyClass());
}
}
As said, references to a specific instance have to serialize the target instance, hence, depend on the serializability of that instance so
import java.io.*;
import java.util.function.Consumer;
public class MyClass {
public void foo() {
System.out.println("Serializable");
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
Runnable runnable = (Runnable&Serializable)new MyClass()::foo;
byte[] serialized;
try(ByteArrayOutputStream baos=new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(runnable);
oos.flush();
serialized=baos.toByteArray();
}
Runnable deserialized;
try(ByteArrayInputStream bais=new ByteArrayInputStream(serialized);
ObjectInputStream ois=new ObjectInputStream(bais)) {
deserialized = (Runnable)ois.readObject();
}
deserialized.run();
}
}
will fail at runtime with a java.io.NotSerializableException: MyClass, unless you change MyClass to implement Serializable.
I know you can serialize a lambda expresion (as you can see here)
Now, what you want to do is only serialize a the variable by itself? or the method?... I don't know why, but I don't think you can. Maybe you can go for other way, like creates a lambda and serialize it, like in the post above:
Runnable r = (Runnable & Serializable)() -> System.out.println("Serializable!");
Hey this is a very simple question. Can I call a variable, in this case an array, from a void method? I have declared my arrays at the class level and initialized them in a void method. Not sure it I am doing this correctly but I am trying to call the array from another class. I am a beginner. Thank you for the help.
ex:
public class HeyThere{
public double me[];
public void yeahYou(int you){
me = new me[69]
}
}
Here you declarate a public variable (array)
public double me[ ];
and here you instantiate it in a method
me = new me[69]
Yes, since your class level array me is scoped as Public, you will be able to access it from another class after you instantiate the HeyThere class.
Ex:
public class HeyThereCaller
{
..
....
public void SomeMethod()
{
...
....
HeyThere heyThereInstance = new HeyThere();
double[] meArray = heyThereInstance.me;
}
}
HeyThere obj1; double a = obj1.me[0]; This is going to give an error in Java though, because me is not instantiated
Yes, you certainly can! Because me is public, you can access it from outside of the class in which it is stored.
Also, you spoke of accessing it from a void method. The return type of a method has no effect on the data it can access; void only means that the method doesn't return a value when called.
If you want to study how variables can be accessed in Java, there is some useful info on this page.
How to call non static method in android ?? I have try all way I can, but nothing. i have try this code in java and success for running, but why in android always error.
Here is the code of main activity.
public class Main extends Activity{
private Coba mstatus;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onClick(View v)
{
switch (v.getId()){
case R.id.download:
....
break;
case R.id.resume:
mstatus.resume();
break;
}
}
This is the second class.
public abstract class Coba implements runnable{
....
public void resume(){
download();
}
public void download() {
mThread = new Thread(this);
mThread.start();
}
}
I want to call resume() method. In my source code nothing warning and error but when I try to call this method it's always force close. Is there another way to call non static method from another class ??
It's rather a java issue than an Android one:
First Coba is abstract so you should use a non abstract class, let's call this class CobaImpl
or make Coba a non abstract class (you choose).
Second you should create an instance of the class to use a non static method (eg mstatus = new CobaImpl(...) elsewhere you can use only static method.
In Spring 3 it is not possible to set #Autowired in either static fields or methods, so since I want to declare an utility class such as:
public class SchoolYearServiceUtil {
private static SchoolYearService schoolYearService;
public static SchoolYear getSchoolYear(Long id) {
return schoolYearService.get(id);
}
}
to avoid having to inject the schoolYearService everywhere (jsp, command class...) in which I need it. In this case, I don't need an interface to be implemented by SchoolYearServiceUtil.
I don't want to have to initialize the object through code but getting the same instance as the Spring's one.
Which would be the best option to implement the getSchoolYear as a static method?
Thanks.
Would this be conceptually wrong?:
#Component
public class SchoolYearServiceUtil {
private static SchoolYearService schoolYearService;
#Autowired(required = true)
private SchoolYearServiceUtil(#Qualifier("schoolYearServiceImpl") SchoolYearService schoolYearService) {
SchoolYearServiceUtil.schoolYearService = schoolYearService;
}
public static SchoolYearService getSchoolYearService() {
return schoolYearService;
}
public static SchoolYear getSchoolYear(Long id) {
return getSchoolYearService().get(id);
}
}
I would have to make sure that only Spring calls once the constructor and the constructor is called nowhere else, that's why I declared the constructor as private.
I fully support skaffman's comment. You don't need static fields with DI. You just define a bean of scope singleton (default).
There is a way to obtain a bean statically, but you should be aware that it is not to be used in regular situations. (there are some valid applications). It is to use the WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
You notice that you need to pass a ServletContext argument.