java中Method类有什么作用

Python020

java中Method类有什么作用,第1张

java Method类是最终类,不能继承,使用方式如下:

/**

 */

package com.timer.demo.objectsocket

import java.lang.reflect.Method

/**

 * @author 崔冉

 *

 */

public class InvokeTester {

public int add(int param1, int param2) {

  return param1 + param2

    }

public String echo(String mesg) { 

  return "echo" + mesg

}

public static void main(String[] args) throws Exception {

  Class classType = InvokeTester.class

  Object invokertester = classType.newInstance()

  

  Method addMethod = classType.getMethod("add", new Class[] { int.class,

    int.class })

  //Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象

  //如果参数为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,

  //如果实际被调用的方法的返回类型是基本类型数据,那么invoke()方法会把它转换为相应的包装类型的对象,

  //再将其返回

  

  Object result = addMethod.invoke(invokertester, new Object[] {

    new Integer(100), new Integer(200) })

  //在jdk5.0中有了装箱 拆箱机制 new Integer(100)可以用100来代替,系统会自动在int 和integer之间转换

  System.out.println(result)

  Method echoMethod = classType.getMethod("echo",

    new Class[] { String.class })

  result = echoMethod.invoke(invokertester, new Object[] { "hello"})

  System.out.println(result)

 }

}

首先你应该明确一点,Method类是一个最终类,不可继承。

其实你写的两个类在目前看来是没有可比性的,就像你声明了一个人类,声明了一个汽车类,而你去比较人和汽车,你怎么比较?

一个对像的EQUAL方法是从OBJECT类里面已经继承过来的,但是如果要比较对像的话,应该实现一个可比较的接口compare,当然,已经有好多的类型已经实现的这个接口,例如:String、Integer等,所以你要比较两个对象的时候可以从这些已经实现了这个接口的字段去比较,然后重写equsls()方法,在方法中可以这样写

class A{

public int a

public boolean equles(Object b)

if(b.class.equal(A.class))

{

return this.a.equles(b.a)

}else if(b.class.equal(B.class))

{

return this.a.equles(b.b)

}

}

class B {

public int b

}

function是面向过程程序设计中的叫法。

java是纯面向对象程序设计语言,一个类对属性和方法进行了封装

所以在java中叫method。这种说法比较贴切