Search This Blog

Friday, July 15, 2011

reflecting: Creating a new object of a reflected class via code

Hello. I am trying to input the name of a class that I have imported already, and can instantiate regularly, such as ‘myClass inst = new myClass(‘foo’);’ and create a new instance-object of that class. The code below illustrates my question more specifically:





import java.lang.reflect.*;
import java.io.*;

public class reflecting1
{
public reflecting1()
{

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Input the name? n");

try
{
typed = reader.readLine();
} catch (Exception e) {}

try
{
Constructor con = (typed.class).getConstructor(String.class);

Object obj = con.newInstance("Hello World!");
Method methd = (typed.class).getMethod("hashCode");

System.out.println(obj);

int hash = methd.invoke(obj);
System.out.println(hash + "");

} catch (Exception ee) {
System.err.println("Class not created.");

}

}

}




When the input of the above program is: ‘String’

Why is the output not:



Hello World!

-969099747


and I tried:





import java.lang.reflect.*;
import java.io.*;

public class reflecting2
{
public reflecting2()
{

BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Input the name? n");

try
{
typed = reader.readLine();
} catch (Exception e) {}

try
{
Class newC = Class.nameOf(typed);
Constructor con = (typed.class).getConstructor(String.class);

Object obj = con.newInstance("Hello World!");
Method methd = (typed.class).getMethod("hashCode");

System.out.println(obj);

int hash = methd.invoke(obj);
System.out.println(hash + "");

} catch (Exception ee) {
System.err.println("Class not created.");

}

}

}




but still didn’t work.. does anyone know how to make this work?

http://bit.ly/oaHScr

No comments:

Post a Comment