在java中反思?

scr*_*ler 1 java

我是java编程语言的新手.

我的问题是:我想从控制台读取sys.input的类名.在读取类的名称时,我想自动生成该类,并且如果该类已经存在则调用其方法.我的审判在这里.虽然我没有收到任何错误,但没有任何反应.亲切的问候.


class s1{
    public s1(){
        System.out.println(""+ s1.class);
    }
}
public class reflection {

    public static void main(String[] args) throws IOException, ClassNotFoundException{

        System.out.println("enter the class name : ");    
        BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
        String line = "reflection_N3."; 
        line+=reader.readLine();

        //System.out.println(line);

     // "name" is the class name to load
       Class clas = Class.forName(line);       
       clas.getClassLoader();     
    }
}
Run Code Online (Sandbox Code Playgroud)

Pét*_*rök 8

您没有创建该类的实例.尝试

Class clas = Class.forName(line);
Object obj = clas.newInstance();
Run Code Online (Sandbox Code Playgroud)

但是,问题是,除非你知道它的确切类型,否则你不能对这个对象做太多的事情,并将它强制转换为该类型.

在此示例中,您可以尝试将其强制转换为类类型,例如

if (obj instanceof s1) {
  s1 myS1 = (s1) obj;
  myS1.s1();
}
Run Code Online (Sandbox Code Playgroud)

然而,这在现实生活中几乎不起作用,因为你事先并不知道可能的类型.对此的典型解决方案是为特定目的定义接口,并要求类实现该接口.然后,您可以将类实例向下转换为该接口(如果转换失败则抛出异常),并调用其接口方法,而无需知道其具体类型.

或者,正如@helios所指出的,您可以使用反射来获取具有特定名称的已加载类的方法.

顺便说一下Java约定是用大写的方式启动类名,因此S1Reflection.

  • 或者使用反射来获取方法,也就是`class.getMethod(...);`并调用它``method.invoke(obj,...);` (2认同)