posts - 12,  comments - 2,  trackbacks - 0
Java 中,无论生成多个类的对象,这些对象都会对应于同一个Class对象

2.获取某个类或某个对象所对应的Class对象常用的3种方式
a)使用Class类的静态方法forName:Class.forName("java.lang.String")
b)使用类语法String.class
c)使用对象的getClass()方法:String s ="aa";
Class<?> clazz= s.getClass(); 
  不带参数的构造方法,生成对象
 a)先获得Class对象,然后通过Class对象newInstance() 方法直接生成对象。
 b) 先获得Class对象,然后通过该对象获得对应的Construtor 对象,

package com.doodoosun;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectTest {


    
    public int add (int param1,int param2){
        return param1+param2;
    }
    
    public String echo (String message){
        return "Hello :"+message;
    }
    
    
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
        // TODO Auto-generated method stub
        Class<?> classType = ReflectTest.class;
        
        Object reflectTest = classType.newInstance();
        
        Method addMethod = classType.getMethod("add",new Class[]{int.class,int.class});

        Object result = addMethod.invoke(reflectTest,new Object[]{1,2});
        
        System.out.println("-------"+(Integer)result);
        
        Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
        
        Object result2  = echoMethod.invoke(reflectTest, new Object[]{"tom"});
        
        System.out.println(result2);
        
        
        
    }
posted on 2014-12-02 00:50 doodoosun 阅读(133) 评论(0)  编辑  收藏 所属分类: Java 相关

只有注册用户登录后才能发表评论。


网站导航:
 

<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(1)

随笔分类(6)

随笔档案(11)

文章分类(30)

文章档案(34)

搜索

  •  

最新评论

阅读排行榜

评论排行榜