java中有类似于c++中的函数指针或者是c#中的代理没?或者说,我现在要在一个函数(function1)里调用某个函数(function2),function2的签名形式不变,但是所在的类以及名称会有变化,我想在function1的参数列表里加入function2的签名,不知道java应该如何实现这个?
解决方案 »
- 问一个算法的问题?????
- java中的方法重写,小弟新手
- 大家好,提问一个关于StringBuffer的输出问题
- 一个搜索引擎代码,可以有错误,帮看看
- Applet最儿科问题
- 为什么Image.getWidth()得不到图片的宽度?
- 如何才能显示中文
- java应该用哪些开发程序??
- 菜鸟问题——HelloJava
- 有没有谁知道哪里有jdbc driver for sqlserver2000(当然是说免费而功能完全的了)?要求支持jdbc2.0,不要微软的!谢谢
- 用java程序编写一个圆,已经画出了圆,但其中一些程序不明白
- EclipseAppLauncher,不好用了,起不来Eclipse,高手帮忙看看。谢谢。
调用的话可以让函数变成static的
比如
public interface FunctionPointer{
voif function();
}public void test(FunctionPointer fp){
fp.function();
}只要给test方法传入不同的实现该接口的类的对象即可。跟你把指针指向不同的函数类似。
Effective Java中有说明,可以看看。
Some languages support function pointers, delegates, lambda expressions, or similar
facilities that allow programs to store and transmit the ability to invoke a particular
function. Such facilities are typically used to allow the caller of a function
to specialize its behavior by passing in a second function. For example, the qsort
function in C’s standard library takes a pointer to a comparator function, which
qsort uses to compare the elements to be sorted. The comparator function takes
two parameters, each of which is a pointer to an element. It returns a negative integer
if the element indicated by the first parameter is less than the one indicated by
the second, zero if the two elements are equal, and a positive integer if the element
indicated by the first parameter is greater than the one indicated by the second.
Different sort orders can be obtained by passing in different comparator functions.
This is an example of the Strategy pattern [Gamma95, p. 315]; the comparator
function represents a strategy for sorting elements.
Java does not provide function pointers, but object references can be used to
achieve a similar effect. Invoking a method on an object typically performs some
operation on that object. However, it is possible to define an object whose methods
perform operations on other objects, passed explicitly to the methods. An
instance of a class that exports exactly one such method is effectively a pointer to
that method. Such instances are known as function objects. For example, consider
the following class:
class StringLengthComparator {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
int i =10;}main()
{
A a = new a()
a.i; //这里引用也就是类似指针}
但是,java和C的思考方式感觉完全不一样。一天到晚类比,等于没学。
但是java里面没有指针概念却可以通过native的方式来封装指针,不过那不是java实现的,而是java利用C++去实现了。
我们都知道,所谓的指针就是一个内存地址值,也就是一个数字,它完全可以用long类型来表示。
你大概可以这么实现,写两个方法,一个传入一个Object类型,返回这个Object类型的地址值(long类型),另一个传入地址值(long类型数值),返回一个Object类型,然后根据需要吧这个Object类型进行强转(当然你也可以使用泛型来替代)。当遇到基础数据类型的时候,在native里面封装成对象类型类型就可以了,不然Object类型不能接受基础数据的。这样你就可以实现类似指针功能了。
不过这样实现我并不推荐,首先这样的实现不跨平台(跨平台也可以,每个平台写一个native,就像jdk那样),这样一来java优势荡然无存还不如直接用有指针的语言来开发,其次,这种实现方式极易使虚拟机崩溃(产生不可抛出异常的内存错误,因为它已不在java虚拟机管辖范围之内了),有时甚至会导致蓝屏死机这种可怕后果,慎用。