This question already has answers here:
How do I access private methods and private data members via reflection?
(6 answers)
What does it mean for a method to be public/private/other in java? [closed]
(6 answers)
Closed 8 years ago.
This program ran fine when test() method was public but as soon as I changed its modifier to private it showed Run time error.Can anybody explain why?
package ObjectClass;
import java.lang.reflect.Method;
public class reflect8 {
public static void main(String[] args) throws Exception {
Class c1 = Class.forName("ObjectClass.Reflect8A");
Object obj = c1.newInstance();
Method m1 = c1.getDeclaredMethod("test");
m1.invoke(obj);
}
}
class Reflect8A {
private void test() {
System.out.println("from test...");
}
}
Here is why you need to call setAccessible(true) even if getDeclaredMethod returns the private method.
Javadoc of getDeclaredMethod (emphasis mine):
Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.
Javadoc of invoke:
Throws IllegalAccessException - if this Method object is enforcing Java language access control and the underlying method is inaccessible.
Javadoc of setAccessible (emphasis mine):
Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used.
Method m1 = c1.getDeclaredMethod("test");
m1.setAccessible(true);
m1.invoke(obj);
Related
This question already has answers here:
When to use static methods
(24 answers)
When to use static variables/methods and when to use instance variables/methods in Java? [closed]
(5 answers)
Java Static vs Instance
(9 answers)
How and where to use Static modifier in Java?
(7 answers)
Closed 2 years ago.
I don't know when to use a static/non-static variable in a program.
package slides;
public class Person {
String name;
int age;
boolean isStaff;
public Person(String name, int age, boolean isStaff) {
// TODO Auto-generated constructor stub
this.name = name;
this.age = age;
this.isStaff = isStaff;
System.out.println(this);
}
/*
public static boolean Staf () {
return isStaff;
}
*/
}
I understand the difference between the non-static/static variable but I just don't know when to use each. So in the above code, why the function Staf can not be static? (and when it should be static?)
According to the last question, you do not understand the difference. Every non-static method implicitly receives this (as an argument). Static methods are not bound to some instances, so you just can not reference non-static fields. Static stuff can reference only static stuff.
static could be used:
For Singleton pattern, for example;
Or if you want to utilize class as simple namespace;
Or just do not like OOP and going to use COP)
The static method Staf() is not allowed to return class instance variables because Staf() can be invoked without the class Person instance being created. Therefore, Staf() can only return static variables.
You can not access non-static (instance) variables unless you do so with a) a reference to an instance (myPerson.isStaff, which would violate encapsulation) or b) from within a non-static (instance) method.
As to when you should use static, there are many discussions and diatribes on this very website which can easily be found.
This question already has answers here:
Accesing static variable from another class in java
(2 answers)
Closed 2 years ago.
public class Parameter {
public static int my_static_int;
}
public class Test {
public void foo (Class<Parameter> argument) {
argument.my_static_int = 1;
}
When I type this code, Eclipse gives me an error when I try to access my_static_int in the function foo, saying my_static_int cannot be resolved or is not a field. Could someone tell me what I'm doing wrong?
The static modifier in Java is directly related to the class. If the field is static, it means that it belongs to the class. Based on this, you can access a static method or field using the class name.
In your case, you can access the field directly:
Parameter.my_static_int
This question already has answers here:
how to copy SubClass object in BaseClass copy constructor
(3 answers)
Java: How to copy an object so it will be from the same subclass?
(4 answers)
Closed 4 years ago.
I have a subclass called CDAccount that has its own variables that aren't defined in the super class.
private Calendar maturityDate;
private int termOfCD;
The subclass also has a copy constructor that takes in a superclass object.
public CDAccount(Account cd){
super(cd);
}
This constructor is called by this line of code that's in a different class.
if (accounts.get(index).getType().equals("CD")) {
return new CDAccount(accounts.get(index));
}
I'm looking for a way to set the subclass variables in the copy constructor. I thought I would be able to do it with the object it takes in, because I created the object as a subclass object before setting it into the array of superclass objects.
Casting should do the trick for you:
public CDAccount(Account cd) {
super(cd);
if(cd instanceof CDAccount) {
this.maturityDate = ((CDAccount)cd).maturityDate;
this.termOfCD=((CDAccount)cd).termOfCD;
}
else {
this.maturityDate = null;
this.termOfCD= null;
}
}
This works because of the way encapsulation is implemented in Java: private variables are accessible to other instances of the same class.
The best practice would be overloading the constructor like this.
public CDAccount(CDAccount cd){
super(cd);
this.maturityDate = cd.getMaturityDate()
this.termOfCD = cd.getTermOfCD()
}
public CDAccount(Account cd){
super(cd);
}
This works for me on Java JDK v10.1
This question already has answers here:
System.out is declared as static final and initialized with null? [duplicate]
(2 answers)
Closed 5 years ago.
As to access the methods of PrintStram class an object must be created, so how the out variable is able to access those methods when it is assigned null.
public final static PrintStream out = null;
This is the declaration in System class.
I tried to write the similar code but then it gives NullPointerException. My code is given below.
class First{
public void display(){
System.out.println("Hello");
}
}
class Second{
public final static First s1=null;
}
public class Third{
public static void main(String[] args) {
Second.s1.display();
}
}
To make this code run i will have to make either display method static or define s1 as-
public final static First s1=new First();
The field isn't null at runtime. It's assigned the relevant stream stdout or something else if it has been redirected. The mechanism is internal to the JVM, so the code isn't readily visible in the JDK sources. You can use System.setOut() to modify the field, which again uses internal mechanisms as the field is final and normally wouldn't be assignable.
You may have missed the System.initializeSystemClass() which according to the documentation is called after the class initialization. It initialize the in, out and err stream. It use native methods to do that, so it doesn't have to respect the final modifiers.
This question already has answers here:
Behavior of Functional Interface and Method Reference
(2 answers)
Closed 7 years ago.
This code uses method reference to an instance method of a particular object:
public class Main {
public static void main(String[] args) {
One one=new One();
// F f = ()->{one.bar();}; //previous wrong syntax
F f = one::bar; //4
f.foo();
}
}
class One{void bar(){}}
interface F{void foo();}
I know it works. But I'm not being able to understand why and how.
What I can't understand is how is it possible that F.foo() method is using a reference to an object that is not an argument to the method itself (signature is not void foo(One one)).
At line 4 I am
creating an instance of a class that implements F interface
implementing the method by using the reference one to invoke bar() method
But how can foo() have a scope on one reference? Am I being wrong trying to translate this solution to a "traditional, explicit implementation"? If not, what would it be the "explicit counterpart"?
Your lambda is compiled into private synthetic method which looks like this:
private static void lambda$1(One one) { one.bar(); }
At runtime the lambda expression is translated into runtime representation during the first time you execute this code. Current runtime representation in OpenJDK 8 is an anonymous class which takes the captured variables as constructor parameters and stores them into fields, then calls the lambda body method generated by compiler. Something like this is generated:
class lambda12345678 implements F {
private One arg1;
lambda12345678(One arg1) {this.arg1 = arg1;}
public void foo() {
lambda$1(arg1);
}
}
And call site is technically replaced with constructor call, thus instead of
F f = ()->{one.bar();};
You effectively have
F f = new lambda12345678(one);
Note that if your lambda does not capture context, it works in more efficient way: only one object is created and reused. But in your example as lambda behavior depends on external state, every time the new instance is created.