Calling private method inside private class inside Inner class - java

Need to call a private method foo() of the class Inner.Private, where Private is an inner private class from the main method of the main class.
The code is something like this:
public class MainClass {
public static void main(String[] args) throws Exception {
// Need to invoke foo() from here
}
static class Inner {
private class Private {
private String foo() {
return "someString";
}
}
}
}
I was trying to get this using Java Reflection, but I am facing issues from this approach.
My attempt to invoke the foo() is:
Inner innerClassObject = new Inner();
Method method = Inner.Private.class.getDeclaredMethod("foo");
method.setAccessible(true);
method.invoke(innerClassObject);
But this gives a NoSuchMethodException:
Exception in thread "main" java.lang.NoSuchMethodException:
default.MainClass$Inner$Private.foo()
at java.lang.Class.getDeclaredMethod(Unknown Source)
I am stuck at this point, is this achievable by Java Reflection, or any other way?

Ummm... why not simply new Inner().new Private().foo()?

Why are you doing this
Inner.Private.class
Instead of
innerClassObject.getClass()
For e.x:
public class Test {
private int foo(){
System.out.println("Test");
return 1;
}
public static void main(String [] args) throws InterruptedException,
NoSuchMethodException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException
{
Test innerClassObject = new Test();
Method method =
innerClassObject.getClass().getDeclaredMethod("foo",null);
method.setAccessible(true);
method.invoke(innerClassObject);
}
}

Why waste an instantiation just to call a method as was described? You will inevitably want to save various instances for latter use as the classes develop.
public class MainClass {
public static void main(String[] args) throws Exception {
// Need to invoke foo() from here
Inner inner = new Inner();
Inner.Private pvt = inner.new Private();
System.out.println(pvt.foo());
}
static class Inner {
private class Private {
private String foo() {
return "someString";
}
}
}
}
Prints
someString

Related

Why am I able to inherit & call a private constructor in a subclass?

I read that it is not possible to create a subclass from a class whose constructor is private but weirdly I am able to do it, is there something more to this snippet?
Please someone provide an easy to understand & satisfactory explanation.
public class app {
public static void main(String[] args) {
app ref = new app();
myInheritedClass myVal = ref.new myInheritedClass(10);
myVal.show();
}
int myValue = 100;
class myClass {
int data;
private myClass(int data) {
this.data = data;
}
}
class myInheritedClass extends myClass {
public myInheritedClass(int data) {
super(data);
}
public void show() {
System.out.println(data);
}
}
}
I ran this snippet on https://www.compilejava.net/ and the output was 10.
Because your classes are both nested classes (in your case, specifically inner classes), which means they're both part of the containing class, and so have access to all private things in that containing class, including each other's private bits.
If they weren't nested classes, you wouldn't be able to access the superclass's private constructor in the subclass.
More about nested classes in the nested class tutorial on the Oracle Java site.
This compiles, because A and B are inner classes, which are nested classes (live copy):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
class A {
private A() {
}
}
class B extends A {
private B() {
super();
}
}
}
This compiles, because A and B are static nested classes (live copy):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
static class A {
private A() {
}
}
static class B extends A {
private B() {
super();
}
}
}
This does not compile because A's constructor is private; B cannot access it (I don't really need Example in this case, but I've included it in the two above, so for context...) (live copy):
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Ran at " + new java.util.Date());
}
}
class A {
private A() {
}
}
class B extends A {
private B() {
super(); // COMPILATION FAILS HERE
}
}

How to call a behavioral method from main method in java?

I have a non static method abc() in the class that contains main() method. Now how to call this method abc() from main. Can i create an instance of the class in the same class?
public class A
{
public static void main(String[] args)
{
//how to call abc() here?
}
private int abc()
{
return 2;
}
}
You have to instanciate current class, use this code:
public static void main(String[] args)
{
A a = new A();
int value = a.abc();
}

Dynamically invoke a method from a varying class

I have a requirement where in i need to invoke method from class in a particular pattern which is obtained as input argument.
public RandomMethod(String ClassName){
//Eg For Class Name Abc , there is a method AbcProcessor which i need to invoke
ClassName.ClassNameProcessor
}
Since i am getting the argument as String , i am not able to figure out how to cast String into a form where i can call something like Abc.AbcProcessor()
I believe there is some way to do this using reflections. But i am not sure how to proceed.
By reflection you can do that, try following sample:
Class A:
public class A {
public void print(){
System.out.println("A");
}
}
Class B:
public class B {
public void print(){
System.out.println("B");
}
}
Invoking print() from A and B:
public class Test {
public static void callPrint(String className){
try {
Class clazz = Class.forName(className);
Object obj = clazz.newInstance();
clazz.getDeclaredMethod("print").invoke(obj);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
callPrint("test.A");
callPrint("test.B");
}
}
You need to use reflecton, indeed:
public void randomMethod(String fullyQualifiedClassName, String methodName) throws ReflectiveOperationException {
Class<?> clazz = Class.forName(fullyQualifiedClassName);
clazz.getMethod(methodName).invoke(null);
}
which would work assuming you are calling public static method with no arguments

Invoking a Class and Method Using Variables In Java

I am attempting to call a custom class and method on my Application start-up to perform dev testing. I have stored the setting for my test class and method in my SettingsClass as shown below.
public class SettingsClass {
public static final boolean BOOT_TEST = true;
public static final String BOOT_CLASS = "MyClass";
public static final String BOOT_METHOD = "MyMethod";
}
My Main Class.
public class MainClass {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
if(SettingsClass.BOOT_TEST) {
Method method = getDeclaredMethodClass(SettingsClass.BOOT_CLASS).getDeclaredMethod(SettingsClass.BOOT_METHOD);
method.invoke();
System.exit(1);
}
}
Is it possible to perform the above action?
Any help would be appreciated.
You need both a reference to the Class type and an instance of the class (unless the method you want to invoke is static). In your pseudo code you have the correct idea, all you need to do is a quick review of the javadoc for java.lang.Class and java.lang.reflect.Method
public class SettingsClass {
public static final boolean BOOT_TEST = true;
public static final String BOOT_CLASS = "MyClass";
public static final String BOOT_METHOD = "doMain";
}
public class MyClass {
public static void doMain() {
}
}
public class MainClass {
public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
if(SettingsClass.BOOT_TEST) {
Class<?> clazz = Class.forName(SettingsClass.BOOT_CLASS);
Method m = clazz.getMethod(SettingsClass.BOOT_METHOD);
m.invoke(null);
System.exit(1);
}
}
for .invoke() you need an object that is an instance of your class.
if your class has an public default consturctor you should be able to do something like this
// load your class
Class<?> clazz = Class.forName("full.package.and.class.name");
// get the method
Method method = clazz.getDeclaredMethod("methodName");
// create an instance of your class
Object object = clazz.newInstance();
// call the method in context of object
method.invoke(object);
You can refer to Java reflection (Method Invocation)
http://docs.oracle.com/javase/tutorial/reflect/member/methodInvocation.html
you can find methods through
Class<?> c = Class.forName("nameClass");
Object t = c.newInstance();
Method[] allMethods = c.getDeclaredMethods();
and you can call through
m.setAccessible(true);
Object o = m.invoke(t, .... )
Yes, it is. The following code will execute the method someMethod in the MainClass.
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainClass {
public static final boolean BOOT_TEST = true;
public static final String BOOT_CLASS = "MainClass";
public static final String BOOT_METHOD = "someMethod";
public static void main(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
if (MainClass.BOOT_TEST) {
Class bootClass = Class.forName(BOOT_CLASS);
Method bootMethod = bootClass.getDeclaredMethod(BOOT_METHOD, null);
bootMethod.invoke(null, null);
}
}
public static void someMethod() {
System.out.println("Some method executing...");
}
}
What you need to do is get the class object for the class whose method you wish to execute dynamically by using the static method Class.forName(String) passing in the class's name. subsequently you can request the method you wish to execute using the getDeclaredMethod(String, Class<?>...) passing in the method's name and parameter types. Following that you can call invoke(Object, Object...) on the method with two null arguments (execute the method on no instance of the class (static execution) without any parameters).

How to get java.lang.reflect.Field when you have a reference to myBean.getId()

I want do something like this :
public myMethod(Object expectedValue) {
java.lang.reflect.Method method = new Method(expectedValue);
System.out.println(method.getName());
}
How do I get a method reference from the getter itself without introducing string coupling (specifying the getter name) ?
Don't know if I understood your question right, but below you'll find the code who you can invoke a getter from an object using reflection. Afaik, there is no way to get a method without refering to its name.
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
Foo foo = new Foo();
foo.setBla("i am bla");
Method blaGetter = Foo.class.getMethod("getBla");
System.err.println(blaGetter.invoke(foo));
}
private static class Foo {
private String bla;
public String getBla() {
return bla;
}
public void setBla(String bla) {
this.bla = bla;
}
}

Categories

Resources