Java反射
Posted www
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java反射相关的知识,希望对你有一定的参考价值。
https://www.sczyh30.com/posts/Java/java-reflection-1/#3、创建实例
Fruit.java
package com.wzh.reflection; public interface Fruit { public void eat() ; }
Apple.java
package com.wzh.reflection; class Apple implements Fruit { public Apple() {} public void eat() { System.out.println("吃苹果。"); }; }
Orange.java
package com.wzh.reflection; class Orange implements Fruit { public Orange() {} public void eat() { System.out.println("吃橘子。"); }; }
MyRun.java
package com.wzh.reflection; import java.lang.reflect.Constructor; class Factory { public static Fruit getInstance(String className) { Fruit fruit = null; try{ Class<?> clazz = Class.forName(className); Constructor<?> constructor = clazz.getConstructor(); Object obj = constructor.newInstance(); fruit = (Fruit)obj; } catch(Exception e) { e.printStackTrace(); } return fruit; } } public class MyRun { public static void main(String[] args) { Fruit fruit = Factory.getInstance("com.wzh.reflection.Orange") ; fruit.eat(); } }
以上是关于Java反射的主要内容,如果未能解决你的问题,请参考以下文章
使用反射在外部JAR / CLASS上调用包含Hibernate事务的方法(Java EE)