Access an object from another class in private method - java

How do I access an object from another class in private method in Java ?
Simple example to call private method from another class.
File: A.java
public class A {
private void message(){System.out.println("hello java"); }
}
File: MethodCall.java
import java.lang.reflect.Method;
public class MethodCall{
public static void main(String[] args)throws Exception{
Class c = Class.forName("A");
Object o= c.newInstance();
Method m =c.getDeclaredMethod("message", null);
m.setAccessible(true);
m.invoke(o, null);
}
}

Since private is used only in declared classes and it can not be called from other classes. If you want to use it, you should use it after modifying to protected or public.

Normally Private methods can access only from within the same class. Can’t access the private methods from the outside class. However, there is a way to access the private methods from outside class.
import java.lang.reflect.Method;
public class PriavteMethodAccessTest{
public static void main(String[] args)throws Exception{
A test = new A();
Class<?> clazz = test.getClass();
Method method = clazz.getDeclaredMethod("message");
method.setAccessible(true);
System.out.println(method.invoke(test));
}
}

Related

when you extend a private class. are the public and protected members of class become private

when you extend a private class. Are the public and protected members of class become private. if not any explanation.
if you extend a nested private class, it wont change public/protected modifiers of the members. Here is an example :
public class Clazz {
private static class NestedClazz {
public int value = 123;
}
public static class NestedClazzExt extends NestedClazz {
}
}
you can now access the inherited member: value from outside
public static void main(String[] args) {
NestedClazzExt nestedClazz = new Clazz.NestedClazzExt();
System.out.println(nestedClazz.value);
}
you can create private class in side a class . We call it as Nested classe. Means a class inside a class. The Concept itself is saying that you can create private class in side another class. The private class will act like as data member to the outer class.
So, You can't extend the private class.
Based on your query I tried to prepare a simple class.
public class pvtClass {
private class As {
public String abc = "private attribute";
public void print(){
System.out.println("privateClass");
}
}
class Ab extends As{
public String ab = "extended attribute";
public void printAb(){
System.out.println("extended class");
print();
System.out.println(abc);
}
}
public static void main(String as[]){
Ab ab1 = (new pvtClass()).new Ab();
As as1 = (new pvtClass()).new As();
ab1.printAb();
as1.print();
System.out.println(as1.abc);
}
}
If you have a look at this class, I have a private class named "As" which has public attribute and public methods. I have another class named "Ab" which extends "As". I have written a main method to invoke the private attribute and methods.
below is the output for the code snippet:
extended class
privateClass
private attribute
privateClass
private attribute
There is a difference between the access of the members of a class and the access to the type itself.
public class C {
private class InnerP1 {
public void m() {
System.out.println("InnerP1.m()");
}
}
private class InnerP2 extends InnerP1 {
public void p() {
this.m();
System.out.println("InnerP2.p()");
}
}
public InnerP1 strange() {
return new InnerP2();
}
}
In this example, the interface I is visible from outside class C. The classes InnerP1 and InnerP2 are not visible from outside C. Jave itself makes not restrictions to the visibility of types you use in your public interface. The method strange() of class C returns a result of class InnerP1. Since outside of C we do not know anything about the class InnerP1 other than it is subtype of Object, the only thing we can do is use the result of strange() as an Object.
public class D {
public static void main(String[] args) {
C c = new C();
Object o = c.strange();
if(o.equals(c.strange())) {
System.out.println("Strange things are going on here!");
}
}
}
As #KnusperPudding pointed out already, the visiblity of public members is not changed, we might just not have enough knowledge of the type itself to access them.
Access to members cannot be restricted by sub-classing. When you mark a class as private then access via the class name is restricted i.e. to the same .java file, however once you have an instance of this class it can be accessed at least as easily as the super class.

Error in a member class java [duplicate]

This question already has answers here:
Why can't we have static method in a (non-static) inner class (pre-Java 16)?
(15 answers)
Closed 8 years ago.
Im trying to understand how inner class works and while experimenting with some simple code i got a error : The method hello cannot be declared static; static methods can only be declared in a static or top level type
on this code
public class Class1 {
public static void main(String[] args) {
Class1 c = new Class1();
c.show();
}
public static void show() {
class C2 {
static public void hello() {
System.out.println("show class");
}
}
C2.hello();
}
}
and i cant understand why!
Refer to the documentation here.
Inner Classes: As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
Class2 is an inner class which means that it needs to be tied to an Class1 object. Then objects of Class2 can access the fields of the bound object at all times:
public class Class1 {
private String name = "class1";
public static void main(String[] args) {
Class1 a = new Class1();
Class2 c = a.new Class2();
c.show();
}
class Class2 {
public void show() {
System.out.println("helloworld: "+name); //accessing the name field of a without needing the variable
}
}
}
or you need to make Class2 static so it doesn't need the Class1 instance.
public class Class1 {
public static void main(String[] args) {
Class2 c = new Class2();
c.show();
}
static class Class2 {
public void show() {
System.out.println("helloworld");
}
}
}
Class C2 in your example above is a local Inner class, which means an inner class defined within a method of an outer class, and such classes cannot have static methods inside them because they are associated with objects, (static methods are not dependent upon objects).
Moreover, a local inner class must be instantiated within the method it has been created and not outside the method. This is a rule.
try modifying your code in following way:
public class Class1 {
public static void main(String[] args) {
Class1 c = new Class1();
c.show();
}
public static void show() {
class C2 {
public void hello() {
System.out.println("show class");
}
}
C2 obj= new C2();
obj.hello();
}
}
This should work.
You cant do this since you need to create an instance of Class 'Class1' before you can access Class 'C2'. However the method 'hello' should be possible to access without creating an instance (being a static method).

Invoke Super class methods using Reflection

I have 2 classes, say A & B:
Class A extends B {
public void subClassMthd(){
System.out.println("Hello");
}
}
Class B {
public void printHelloWorld {
System.out.println("Hello");
}
}
Now, I am using reflection to invoke the methods on Class A. I would also like to invoke the printHelloWorld method present in Class B.
I tried using
Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Method superClassmthd = classAInstance.getClass()
.getSuperclass().getMethod("printHelloWorld", null);
superClassmthd.invoke(classAInstance);
Also tried as
Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Class superClazz = Class.forName(classAInstance.getClass().getSuperclass().getName());
Object superclassInstance = superClazz.newInstance();
Method superClassmthd = superclassInstance.getMethod("printHelloWorld", null);
superClassmthd.invoke(superclassInstance );
But none of them work; they throw an InstantiationException.
What am I doing wrong here?
Try this:
Method mthd = classAInstance.getClass().getSuperclass().getDeclaredMethod("XYZ");
mthd.invoke(classAInstance)
The difference is using getDeclaredMethod(), which gets methods of all visibilities (public, protected, package/default and private) instead of getMethod(), which only gets methods with public visibility.
What is the visibility of the methods you want to call (public, private etc).
If you want to see methods which you cannot call directly, you should use getDeclaredMethod().
Also, what the the constructors of your classes like? InstantiationException indicates that you are having trouble getting an instance of class A (or B).
I have the following code and it works:
A.java
import java.lang.reflect.Method;
public class A extends B {
public static void main(String[] args) throws Exception {
A classAInstance = new A();
Method mthd = classAInstance.getClass().getSuperclass().getMethod("XYZ", null);
mthd.invoke(classAInstance);
}
}
B.java
public class B {
public void XYZ() {
System.out.println("done");
}
}

How can I access a method of an "unnamed" class?

public class Test {
public static void main(String[] args) {
DemoAbstractClass abstractClass = new DemoAbstractClass() {
private String val;
#Override
public void runner() {
val = "test";
System.out.println(val);
this.run();
}
public String getVal() {
return val;
}
};
abstractClass.runner();
/**
* I want to access getVal method here
*/
}
}
abstract class DemoAbstractClass {
public void run() {
System.out.println("running");
}
public abstract void runner();
}
Here, I'm declaring an abstract class DemoAbstractClass. I can obviously create a new class that extends this class and add this method to it. But, I would prefer not doing that in my scenario.
Is there any other way to access getVal method in above code??
You can't. You need to make a proper (non-anomous) class out of it. Make it an inner private class if you want to limit its scope.
Alternatively, you could use a StringBuffer and share a referense to it between the methods. Not extremely clean however.
Related question:
Accessing inner anonymous class members
Short of using reflection, you cannot as you have no access to the concrete type of the object to be able to bind the methodcall to
If you don want to do something like this in a sane manner, declare a named class and use that as the type of abstractClass
Unfortunately, if you cannot name the type, you cannot access the methods at the language level.
What you can do, though, is use the reflection API to get a Method object and invoke it on this object.
This, however, is pretty slow. A private class or private interface would be much faster.
I can obviously create a new class that extends this class and add this method to it.
You've already done this; the end result was an anonymous inner class: new DemoAbstractClass() { ... }; If you just moved that declaration into its own class -- you can even make it a private class -- you can access getVal.
Per your example above:
public class Test {
public static void main(String[] args) {
DemoClass abstractClass = new DemoClass();
abstractClass.runner();
/**
* I want to access getVal method here
*/
abstractClass.getVal(); // can do this here now
}
private class DemoClass extends DemoAbstractClass {
private String val;
#Override
public void runner() {
val = "test";
System.out.println(val);
this.run();
}
public String getVal() {
return val;
}
}
}
}
Another option is to make a StringBuilder a member of the main method and use the closure nature of anonymous inner methods:
public static void main(String[] args) {
final StringBuilder value = new StringBuilder();
DemoAbstractClass abstractClass = new DemoAbstractClass() {
#Override
public void runner() {
value.append( "test" );
System.out.println(val);
this.run();
}
};
abstractClass.runner();
// use val here...
String val = value.toString();
}

How can I access a private constructor of a class?

I am a Java developer. In an interview I was asked a question about private constructors:
Can you access a private constructor of a class and instantiate it?
I answered 'No' but was wrong.
Can you explain why I was wrong and give an example of instantiating an object with a private constructor?
One way to bypass the restriction is to use reflections:
import java.lang.reflect.Constructor;
public class Example {
public static void main(final String[] args) throws Exception {
Constructor<Foo> constructor = Foo.class.getDeclaredConstructor();
constructor.setAccessible(true);
Foo foo = constructor.newInstance();
System.out.println(foo);
}
}
class Foo {
private Foo() {
// private!
}
#Override
public String toString() {
return "I'm a Foo and I'm alright!";
}
}
You can access it within the class itself (e.g. in a public static factory method)
If it's a nested class, you can access it from the enclosing class
Subject to appropriate permissions, you can access it with reflection
It's not really clear if any of these apply though - can you give more information?
This can be achieved using reflection.
Consider for a class Test, with a private constructor:
Constructor<?> constructor = Test.class.getDeclaredConstructor(Context.class, String[].class);
Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
Object instance = constructor.newInstance(context, (Object)new String[0]);
The very first question that is asked regarding Private Constructors in Interviews is,
Can we have Private constructor in a Class?
And sometimes the answer given by the candidate is, No we cannot have private constructors.
So I would like to say, Yes you can have private Constructors in a class.
It is no special thing, try to think it this way,
Private: anything private can be accessed from within the class only.
Constructor: a method which has same name as that of class and it is implicitly called when object of the class is created.
or you can say, to create an object you need to call its constructor, if constructor is not called then object cannot be instantiated.
It means, if we have a private constructor in a class then its objects can be instantiated within the class only. So in simpler words you can say, if the constructor is private then you will not be able to create its objects outside the class.
What's the benefit
This concept can be implemented to achieve singleton object (it means only one object of the class can be created).
See the following code,
class MyClass{
private static MyClass obj = new MyClass();
private MyClass(){
}
public static MyClass getObject(){
return obj;
}
}
class Main{
public static void main(String args[]){
MyClass o = MyClass.getObject();
//The above statement will return you the one and only object of MyClass
//MyClass o = new MyClass();
//Above statement (if compiled) will throw an error that you cannot access the constructor.
}
}
Now the tricky part, why you were wrong, as already explained in other answers, you can bypass the restriction using Reflection.
I like the answers above, but there are two more nifty ways of creating a new instance of a class which has private constructor. It all depends on what you want to achieve and under what circumstances.
1: Using Java instrumentation and ASM
Well in this case you have to start the JVM with a transformer. To do this you have to implement a new Java agent and then make this transformer change the constructor for you.
First create the class transformer. This class has a method called transform. Override this method and inside this method you can use the ASM class reader and other classes to manipulate the visibility of your constructor. After the transformer is done, your client code will have access to the constructor.
You can read more about this here: Changing a private Java constructor with ASM
2: Rewrite the constructor code
Well, this is not really accessing the constructor, but still you can create an instance. Let's assume that you use a third-party library (let's say Guava) and you have access to the code but you don't want to change that code in the jar which is loaded by the JVM for some reason (I know, this is not very lifelike but let's suppose the code is in a shared container like Jetty and you can't change the shared code, but you have separate class loading context) then you can make a copy of the 3rd party code with the private constructor, change the private constructor to protected or public in your code and then put your class at the beginning of the classpath. From that point your client can use the modified constructor and create instances.
This latter change is called a link seam, which is a kind of seam where the enabling point is the classpath.
Using java Reflection as follows :
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Test
{
private Test() //private constructor
{
}
}
public class Sample{
public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException
{
Class c=Class.forName("Test"); //specify class name in quotes
//----Accessing private constructor
Constructor con=c.getDeclaredConstructor();
con.setAccessible(true);
Object obj=con.newInstance();
}
}
Yes you could, as mentioned by #Jon Steet.
Another way of accessing a private constructor is by creating a public static method within this class and have its return type as its object.
public class ClassToAccess
{
public static void main(String[] args)
{
{
ClassWithPrivateConstructor obj = ClassWithPrivateConstructor.getObj();
obj.printsomething();
}
}
}
class ClassWithPrivateConstructor
{
private ClassWithPrivateConstructor()
{
}
public void printsomething()
{
System.out.println("HelloWorld");
}
public static ClassWithPrivateConstructor getObj()
{
return new ClassWithPrivateConstructor();
}
}
You can of course access the private constructor from other methods or constructors in the same class and its inner classes. Using reflection, you can also use the private constructor elsewhere, provided that the SecurityManager is not preventing you from doing so.
Yes, we can access the private constructor or instantiate a class with private constructor. The java reflection API and the singleton design pattern has heavily utilized concept to access to private constructor.
Also, spring framework containers can access the private constructor of beans and this framework has used java reflection API.
The following code demonstrate the way of accessing the private constructor.
class Demo{
private Demo(){
System.out.println("private constructor invocation");
}
}
class Main{
public static void main(String[] args){
try{
Class class = Class.forName("Demo");
Constructor<?> con = string.getDeclaredConstructor();
con.setAccessible(true);
con.newInstance(null);
}catch(Exception e){}
}
}
output:
private constructor invocation
I hope you got it.
I hope This Example may help you :
package MyPackage;
import java.lang.reflect.Constructor;
/**
* #author Niravdas
*/
class ClassWithPrivateConstructor {
private ClassWithPrivateConstructor() {
System.out.println("private Constructor Called");
}
}
public class InvokePrivateConstructor
{
public static void main(String[] args) {
try
{
Class ref = Class.forName("MyPackage.ClassWithPrivateConstructor");
Constructor<?> con = ref.getDeclaredConstructor();
con.setAccessible(true);
ClassWithPrivateConstructor obj = (ClassWithPrivateConstructor) con.newInstance(null);
}catch(Exception e){
e.printStackTrace();
}
}
}
Output:
private Constructor Called
Reflection is an API in java which we can use to invoke methods at runtime irrespective of access specifier used with them.
To access a private constructor of a class:
My utility class
public final class Example{
private Example(){
throw new UnsupportedOperationException("It is a utility call");
}
public static int twice(int i)
{
int val = i*2;
return val;
}
}
My Test class which creates an object of the Utility class(Example)
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
class Test{
public static void main(String[] args) throws Exception {
int i =2;
final Constructor<?>[] constructors = Example.class.getDeclaredConstructors();
constructors[0].setAccessible(true);
constructors[0].newInstance();
}
}
When calling the constructor it will give the error
java.lang.UnsupportedOperationException: It is a utility call
But remember using reflection api cause overhead issues
Look at Singleton pattern. It uses private constructor.
Yes you can instantiate an instance with a private constructor using Reflection, see the example I pasted below taken from java2s to understand how:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Deny {
private Deny() {
System.out.format("Deny constructor%n");
}
}
public class ConstructorTroubleAccess {
public static void main(String... args) {
try {
Constructor c = Deny.class.getDeclaredConstructor();
// c.setAccessible(true); // solution
c.newInstance();
// production code should handle these exceptions more gracefully
} catch (InvocationTargetException x) {
x.printStackTrace();
} catch (NoSuchMethodException x) {
x.printStackTrace();
} catch (InstantiationException x) {
x.printStackTrace();
} catch (IllegalAccessException x) {
x.printStackTrace();
}
}
}
The basic premise for having a private constructor is that having a private constructor restricts the access of code other than own class' code from making objects of that class.
Yes we can have private constructors in a class and yes they can be made accessible by making some static methods which in turn create the new object for the class.
Class A{
private A(){
}
private static createObj(){
return new A();
}
Class B{
public static void main(String[]args){
A a=A.createObj();
}}
So to make an object of this class, the other class has to use the static methods.
What is the point of having a static method when we are making the constructor private?
Static methods are there so that in case there is a need to make the instance of that class then there can be some predefined checks that can be applied in the static methods before creation of the instance. For example in a Singleton class, the static method checks if the instance has already been created or not. If the instance is already created then it just simply returns that instance rather than creating a new one.
public static MySingleTon getInstance(){
if(myObj == null){
myObj = new MySingleTon();
}
return myObj;
}
We can not access private constructor outside the class but using Java Reflection API we can access private constructor. Please find below code:
public class Test{
private Test()
System.out.println("Private Constructor called");
}
}
public class PrivateConsTest{
public void accessPrivateCons(Test test){
Field[] fields = test.getClass().getDeclaredFields();
for (Field field : fields) {
if (Modifier.isPrivate(field.getModifiers())) {
field.setAccessible(true);
System.out.println(field.getName()+" : "+field.get(test));
}
}
}
}
If you are using Spring IoC, Spring container also creates and injects object of the class having private constructor.
I tried like this it is working. Give me some suggestion if i am wrong.
import java.lang.reflect.Constructor;
class TestCon {
private TestCon() {
System.out.println("default constructor....");
}
public void testMethod() {
System.out.println("method executed.");
}
}
class TestPrivateConstructor {
public static void main(String[] args) {
try {
Class testConClass = TestCon.class;
System.out.println(testConClass.getSimpleName());
Constructor[] constructors = testConClass.getDeclaredConstructors();
constructors[0].setAccessible(true);
TestCon testObj = (TestCon) constructors[0].newInstance();
//we can call method also..
testObj.testMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Simple answer is yes we can have private constructors in Java.
There are various scenarios where we can use private constructors. The major ones are
Internal Constructor chaining
Singleton class design pattern
Also have another option create the getInstance() where we can create instance of private constructor inside same class and return that object.
class SampleClass1{
private SampleClass1() {
System.out.println("sample class constructor");
}
public static SampleClass1 getInstance() {
SampleClass1 sc1 = new SampleClass1();
return sc1;
}
}
public class SingletonDemo {
public static void main(String[] args) {
SampleClass1 obj1 = SampleClass1.getInstance();
}
}
We can create instance of private class by creating createInstance() in the same class and simply call the same method by using class name in main():
class SampleClass1{
private SampleClass1() {
System.out.println("sampleclass cons");
}
public static void createInstance() {
SampleClass1 sc = new SampleClass1();
}
}
public class SingletonDemo {
public static void main(String[] args) {
//SampleClass1 sc1 = new SampleClass1();
SampleClass1.createInstance();
}
}
Well, you can also if there are any other public constructors. Just because the parameterless constructor is private doesn't mean you just can't instantiate the class.
you can access it outside of the class its very easy to access
just take an example of singaltan class we all does the same thing make the private constructor and access the instance by static method here is the code associated to your query
ClassWithPrivateConstructor.getObj().printsomething();
it will definately work because i have already tested

Categories