dynamically call method of a child class in java - java

i want to use the method of my child class dynamically!
how can i access to child method?
the parent class is :
public abstract class A{
String temp;
public abstract String getData();
public void setData(String temp){
this.temp=temp;
}
and childs class is:
public class B extends A{
#Override
public String getData() {
return "B--GetData";
}
#Override
public void setData(String temp) {
this.temp= temp+"-B";
}
public class C extends A{
#Override
public String getData() {
return "C--GetData";
}
#Override
public void setData(String temp) {
this.temp= temp+"-C";
}
}
i use this code to access my child class
String parseData(String Name){
Class<?> cls = Class.forName(Name);
cls.getMethods();
}
how can i able to call for example getData() method from class C dynamically?
thanks

public String parseData(String Name) throws Exception {
Class<?> cls = Class.forName(Name);
Method[] methods = cls.getMethods();
for (Method method : methods) {
if(method.getName().equals("setData")) {
method.invoke(cls.newInstance(), "Test");
}
}
return null;
}
Please try to use like that.
You call method like below
parseData(C.class.getName());

You can call your method like this :
methods[0].invoke(new B(), null);
you can use `method[1]` or `new C()` based on which method to call and on which object.
The below code also shows how to access private methods as well.
Example :
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
class ExitPuzzle extends MyAbstractClass {
public static void main(String... args) throws IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Class clazz = MyAbstractClass.class;
Method[] methods = clazz.getDeclaredMethods();
System.out.println(Arrays.toString(methods));
methods[0].setAccessible(true); // needed only if method is non-public
methods[0].invoke(new ExitPuzzle(), null);
}
}
abstract class MyAbstractClass {
private void myMethod() {
System.out.println("in MyAbstractClass");
}
}

Related

How to invoke child class method from parent class through reflection

I want to create a menu which should be populated by arbitrary methods, which are marked by an annotation. The methods should be invoked from inside the base class. Unfortunately 'java.lang.ClassCastException' is thrown since the method.invoke function expects an object which is instance of the child class. But i only get the base class.
Here is what i tried so far :
public abstract Class BaseClass{
private void invokeSomeMethod(){
final Method[] methods= getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MenuFunction.class)) {
MenuFunction menuFunction = method.getAnnotation(MenuFunction.class);
menuFunction.invoke(this); //Throws 'java.lang.ClassCastException'
}
}
}
#Retention(RetentionPolicy.RUNTIME)
#Target({ METHOD })
public #interface MenuFunction {
String Label();
}
}
public Class ChildClass extends BaseClass{
#MenuFunction(Label = "First method")
public void setHigh(){
//Arbitrary function
}
#MenuFunction(Label = "Another method")
public void setLow(){
//Do something
}
}
I guess what you want to do is this:
public abstract class BaseClass {
public void invokeSomeMethod() throws InvocationTargetException, IllegalAccessException {
final Method[] methods = getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(MenuFunction.class)) {
MenuFunction menuFunction = method.getAnnotation(MenuFunction.class);
method.invoke(this); //invoke method here'
}
}
}
}
public class ChildClass extends BaseClass{
#MenuFunction(Label = "hello")
public void hello() {
System.out.println("hello");
}
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
new ChildClass().invokeSomeMethod();
}
}
Result:
hello

Java - How to call method class with interface without know class name

I'm new in java, I want to call method class from implemented Class with interface without know class name "ClassA", which only know Object c and I have 2 file.
File (1) CobaInterface.java
package cobainterface;
public class CobaInterface {
public static void main(String[] args) {
ImplementedClass implementedClass = new ImplementedClass();
ClassA clsA = new ClassA();
implementedClass.myMethodFromClassA(clsA);
}
}
class ClassA{
public Integer getTwo(){
return 2;
}
}
interface MyInterface {
public void myMethod();
//here interface
public void myMethodFromClassA(Object c);
}
File (2) : ImpementedClass.java
package cobainterface;
public class ImplementedClass extends CobaInterface {
public void myMethodFromClassA(Object c) {
//System.out.println(c.getTwo()); <- wrong when call method c.getTwo()
}
}
How about if I want to call method getTwo() from ClassA without know Class Name, which only know Object c from file (2) as describe in code above. Thanks for advance.
You should use generic types so the implementation knows what the object will be,
interface MyInterface<T> {
public void myMethod();
//here interface
public void myMethodFromClassA(T c);
}
The impl becomes,
package cobainterface;
public class ImplementedClass Implements MyInterface<ClassA> {
public void myMethodFromClassA(ClassA c) {
//System.out.println(c.getTwo()); <- wrong when call method c.getTwo()
}
}
All together,
class Scratch {
public static void main(String[] args) {
ImplementedClass implementedClass = new ImplementedClass();
ClassA clsA = new ClassA();
implementedClass.myMethodFromClassA(clsA);
}
}
class ImplementedClass implements MyInterface<ClassA> {
#Override
public void myMethod() {
}
#Override
public void myMethodFromClassA(ClassA c) {
System.out.println(c.getTwo());
}
}
class ClassA {
public Integer getTwo() {
return 2;
}
}
interface MyInterface<T> {
void myMethod();
void myMethodFromClassA(T c);
}
You could also do a cast
System.out.println((MyClass)c.getTwo());
but you will lose all benefit of type saftey.

Not able to use getter method of Interface

I have written below code, just to play with interface, Would you
please tell where I have gone wrong here?
This is my interface:
package com.home.intetest;
public interface IFoo {
public abstract String doWork(String str) throws Exception;
}
This is where I have implemented,
package com.home.intetest;
public class FooImpl implements IFoo {
#Override
public String doWork(String str) throws Exception {
if(str !=null) {
System.out.println(str);
}else{
System.out.println("Wrongggg");
}
return str;
}
}
Now I am trying to call them from main, using getter method, its giving me error,in line where I am using getiFoo method
package com.home.intetest;
public class TestMain {
private IFoo iFoo;
public IFoo getiFoo() {
return iFoo;
}
public void setiFoo(IFoo iFoo) {
this.iFoo = iFoo;
}
public static void main(String[] args) {
String str = "Work method";
callWorkMethod(str);
}
private static void callWorkMethod(String str) {
String s = getiFoo().doWork(str);
}
}
1
The line
getiFoo().doWork(str);
can not be called, you need a instance of TestMail first! So boot-up your Application like this:
new TestMain().getiFoo().doWork(str);
2
The error you recieve is a NullPointerException now because iFoo is always null.
Create a instance in the getter using the default constructor like this:
public IFoo getiFoo() {
if (iFoo == null) {
iFoo = new FooImpl();
}
return iFoo;
}
Or inside the declaration like this:
private IFoo iFoo = new FooImpl();

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

How to call instance of variety of classes in java

I create a class to handle some specific job that use variety of classes on my project.
But after finish the job class must call-back specific method on the called classes.
I use interface to handle this call-back method.
How can I store the called class?
I can get the instance from constructor but I'm looking for generic way.
Your question is not clear but it may be possible that you have missed the fact that classes can implement more than one interface.
public interface DoesAJob {
public void doIt();
}
public interface Finishes {
public void finish();
}
class AThing implements DoesAJob, Finishes {
#Override
public void doIt() {
}
#Override
public void finish() {
}
}
private void doTheJob(DoesAJob thing) {
thing.doIt();
}
private void finishUp(Finishes thing) {
thing.finish();
}
public void test() {
AThing thing = new AThing();
doTheJob(thing);
finishUp(thing);
}
You can use just Java Interface, or use Java Reflection.
First the Interface
package test;
public interface MyClassInterface {
public String getName();
}
next, the Interface Implementation
package test;
public class MyClassImplementation implements MyClassInterface {
String name;
public MyClassImplementation() {
name= "Whatever";
}
public String getName() {
return name;
}
}
finally invoke the class. just Interface example:
package test;
public class MainTest {
public static void main(String[] args){
MyClassInterface myClassImplementation = new MyClassImplementation();
System.out.println(myClassImplementation.getName());
}
}
Using Reflection example:
package test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainTest {
public static void main(String[] args)
throws InstantiationException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException, NoSuchMethodException, SecurityException {
//using reflection
Object otherClassImplementation=null;
try {
Class<?> cls = Class.forName("test.MyClassImplementation");
otherClassImplementation = cls.newInstance();
Method method = cls.getMethod("getName");
System.out.println(method.invoke(otherClassImplementation));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}

Categories

Resources