---
title: "java反射机制2 -- 通过名称创建类,并通过该类创建实例"
author: "zhangsk"
date: "2007-12-05T12:43:47Z"
tags: ["C#", "Delphi", "IOC", "Java", "Spring"]
categories: ["非技术"]
slug: "java-2"
draft: false
lastmod: "2007-12-05T12:43:47Z"
id: 146151
url: "https://zhangsk.iteye.com/blog/146151"
---

这几天一直在找java中是如何实现delphi中使用元类统一管理实例创建并通过统一接口操作的方法. java反射机制就是用来解决这一系列问题的,平且java中还有spring框架的Ioc帮助你完成这个功能. 首先看一下java是如何通过字符串创建一个类;为了简单省略了字符串与java类对应的方法, \[code] Class c = null; c = Class.forName("com.zsk.reflection.UserReflection"); \[/code] 有了这个类我们如何创建实例呢? \[code] Object o = c.newInstance(); \[/code] 找到了方法这些东西都是很简单的. 一般的方法都是通过父类或者接口来操作这个o对象. 如果你在多想想,这几行代码的思路可以做出很强大支撑库. 简单的代码如下: \[code]package com.zsk.reflection; public class UserReflection { /\** * @param args \*/ public static void main(String\[] args) { // TODO Auto-generated method stub Class c = null; try { c = Class.forName("com.zsk.reflection.UserReflection"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block // e.printStackTrace(); System.err.println("Class not found."); System.exit(1); } try { Object o = c.newInstance(); System.out.println(o.toString()); } catch (InstantiationException e) { // TODO Auto-generated catch block // e.printStackTrace(); System.err.println("Class not accessible."); System.exit(1); } catch (IllegalAccessException e) { // TODO Auto-generated catch block // e.printStackTrace(); System.err.println("Class not instantiable."); System.exit(1); } } } \[/code] 前文还说了spring的Ioc,我是刚接触java又很多东西都是从Delphi方面理解过来的.错误的地方还请大家指正. 我想要做的功能spring已经帮我实现了,我做了一个Demo如下: \[code] package com.zsk.springtest; public interface IFruit { public void grow(String msg); } package com.zsk.springtest; public class Apple implements IFruit { public void grow(String msg) { // TODO Auto-generated method stub System.out.println("苹果生长---" + msg); } } package com.zsk.springtest; public class Grape implements IFruit { public void grow(String msg) { // TODO Auto-generated method stub System.out.println("葡萄生长---" + msg); } } package com.zsk.springtest; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestFruit { /\** * @param args \*/ public static void main(String\[] args) { // TODO Auto-generated method stub ApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml"); IFruit fruit = (IFruit) context.getBean("fruitId"); fruit.grow("长的不错吗^\_^"); } } \[/code] 这就实现了用过一个字符串创建一个类,并同过统一的接口进行操作. 可以修改一下xml文件看看效果