pgavvo
pgavvo

Reputation: 1

Java - Create object from name and call method

I need to write a Java code that, given a class name, create an object of that type and call a method on it.

I used Java.lang.Class.cast(), but this instruction returns an Object, and there isn't the method that I want to run in the Object class (obviously).

I post some code for explain

import java.lang.reflect.*;

public class Loader {
    public static void main(String[] args) throws Exception {

        String className = "Test";
        Class[] arguments = new Class[] { int.class, int.class };
        Class klass = Class.forName(className);

        Constructor constuctor = klass.getConstructor(arguments);
        Object obj = constuctor.newInstance(new Object[] { 10, 20 });
        klass.getClass().cast(obj).Run(); // <----- PROBLEM
        // this works: ((Test)obj).Run();
    }
}

class Test {
    int a, b;
    public Test(int a1, int b1) {
        a = a1; b = b1;
    }

    public void Run() {
        System.out.println("Run...");
        System.out.println(a + " " + b);
    }
}

Thanks in advance.

Upvotes: 0

Views: 6647

Answers (5)

Kourosh Delfani
Kourosh Delfani

Reputation: 51

Create object from name and call method

public interface Element {
    int getId();
    String getName();
    String getFamily();
}

public class Person implements Element {
    private int Id;
    private String name;
    private String family;

    public Person() {

    }
    public Person(int id, String name, String family) {
        Id = id;
        this.name = name;
        this.family = family;
    }
    @Override
    public int getId() {
        return Id;
    }
    @Override
    public String getName() {
        return name;
    }
    @Override
    public String getFamily() {
        return family;
    }
    public void setId(int id) {
        Id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setFamily(String family) {
        this.family = family;
    }
}

Create object from name and call method:

public static void main(String[] args) {

    try {

        String classImportName = "database.test.Person";
        Class objClass = Class.forName(classImportName);
        Constructor constuctor = objClass.getConstructor();
        Object obj = constuctor.newInstance();


        Method callMethod = obj.getClass().getDeclaredMethod("setFamily", String.class);
        callMethod.setAccessible(true);
        callMethod.invoke(obj, "test");

        /*Field field = obj.getClass().getDeclaredField("family");
        field.setAccessible(true);
        field.set(obj,"delphani");*/

        Element elm = (Element) obj;
        System.out.println(elm.getFamily());

        //In the case the person class does not implement the 'element' Interface
        Method callMethod2 = obj.getClass().getDeclaredMethod("getFamily");
        callMethod2.setAccessible(true);
        String res = (String) callMethod2.invoke(obj);

        System.out.println("Result : " + res);

    }
    catch (Exception ex)
    {
        System.out.println(ex.getMessage());
    }
}

Upvotes: 1

Pranshu jain
Pranshu jain

Reputation: 1

You can use Object class method also and by overriding that method you can access normal method of class and as we know Object class is super class of all java classes so by override a particular method you can enter into your class as

    class hello{
       public int hashCode(){
              fun();
       } 
       public void fun(){
               System.out.println("Successfully Enter in class");
       }
    }
    class call{
        public static void main(String[] args)
        {
             Class.forName("hello").newInstance().hashCode();
        }
    }

Upvotes: 0

Danail Alexiev
Danail Alexiev

Reputation: 7792

Once you have the class and an instance of it, you can try and find the specific method using this method of Class:

public Method getMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException

You provide the name of the method and the expected parameters. If all goes well, you will find it and you can invoke it using this method from the Method class:

public Object invoke(Object obj, Object... args)

You provide your instance and the parameters you need and get the result.

Upvotes: 0

hotzst
hotzst

Reputation: 7526

Use this instead of klass.getClass().cast(obj).Run();:

try {
  Method method = klass.getMethod("Run");
  method.invoke(obj, new Object[0]);
} catch (Exception ex) {
  ex.printStackTrace();
}

You need to retrieve the method, as you did for the constructor and then call that method using invoke with the Object on which you are invoking the method as first argument and an array of Object as second to specify any arguments that are passed to the method (which are non in your case).

Upvotes: 0

Kayaman
Kayaman

Reputation: 73578

Just like you used getConstructor() to get the Constructor object, you can get Method objects with getMethod() or getMethods().

Method m = klazz.getMethod("methodName", parameters);  // Parameters optional
m.invoke(obj, parameters);  // Ditto

Another option is to cast the object (using a regular cast, you "never" need to use Class.cast()) to a known interface and call it in the regular way.

Upvotes: 1

Related Questions