我的编程空间,编程开发者的网络收藏夹
学习永远不晚

java 又一摘要 Reflection

短信预约 -IT技能 免费直播动态提醒
省份

北京

  • 北京
  • 上海
  • 天津
  • 重庆
  • 河北
  • 山东
  • 辽宁
  • 黑龙江
  • 吉林
  • 甘肃
  • 青海
  • 河南
  • 江苏
  • 湖北
  • 湖南
  • 江西
  • 浙江
  • 广东
  • 云南
  • 福建
  • 海南
  • 山西
  • 四川
  • 陕西
  • 贵州
  • 安徽
  • 广西
  • 内蒙
  • 西藏
  • 新疆
  • 宁夏
  • 兵团
手机号立即预约

请填写图片验证码后获取短信验证码

看不清楚,换张图片

免费获取短信验证码

java 又一摘要 Reflection

Core java 一本很好的书[@more@]

Only inner classes can be private.
Regular classes always have either package or public visibility.

inner class:If an inner class has constructors, the compiler modifies them,
adding a parameter for the outer class reference.
An inner class method gets to access both its own data fields
and those of the outer object creating it.


inner class -> local inner class -> anonymous inner class

Whenever you would use a function pointer in C++,
you should consider using an interface in Java.
we suggest that you use Method objects in your own programs
only when absolutely necessary. Using interfaces and inner
classes is almost always a better idea. In particular, we echo
the developers of Java and suggest not using Method objects
for callback functions. Using interfaces for the callbacks
leads to code that runs faster and is a lot more maintainable.
=====================================
Using Reflection to Analyze the Capabilities of Classes
Example 5-5. ReflectionTest.java
1. import java.util.*;
2. import java.lang.reflect.*;
3.
4. public class ReflectionTest
5. {
6. public static void main(String[] args)
7. {
8. // read class name from command-line args or user input
9. String name;
10. if (args.length > 0)
11. name = args[0];
12. else
13. {
14. Scanner in = new Scanner(System.in);
15. System.out.println("Enter class name (e.g. java.util.Date): ");
16. name = in.next();
17. }
18.
19. try
20. {
21. // print class name and superclass name (if != Object)
22. Class cl = Class.forName(name);
23. Class supercl = cl.getSuperclass();
24. System.out.print("class " + name);
25. if (supercl != null && supercl != Object.class)
26. System.out.print(" extends " + supercl.getName());
27.
28. System.out.print("{");
29. printConstructors(cl);
30. System.out.println();
31. printMethods(cl);
32. System.out.println();
33. printFields(cl);
34. System.out.println("}");
35. }
36. catch(ClassNotFoundException e) { e.printStackTrace(); }
37. System.exit(0);
38. }
39.
40.
44. public static void printConstructors(Class cl)
45. {
46. Constructor[] constructors = cl.getDeclaredConstructors();
47.
48. for (Constructor c : constructors)
49. {
50. String name = c.getName();
51. System.out.print(" " + Modifier.toString(c.getModifiers()));
52. System.out.print(" " + name + "(");
53.
54. // print parameter types
55. Class[] paramTypes = c.getParameterTypes();
56. for (int j = 0; j < paramTypes.length; j++)
57. {
58. if (j > 0) System.out.print(", ");
59. System.out.print(paramTypes[j].getName());
60. }
61. System.out.println(");");
62. }
63. }
64.
65.
69. public static void printMethods(Class cl)
70. {
71. Method[] methods = cl.getDeclaredMethods();
72.
73. for (Method m : methods)
74. {
75. Class retType = m.getReturnType();
76. String name = m.getName();
77.
78. // print modifiers, return type and method name
79. System.out.print(" " + Modifier.toString(m.getModifiers()));
80. System.out.print(" " + retType.getName() + " " + name + "(");
81.
82. // print parameter types
83. Class[] paramTypes = m.getParameterTypes();
84. for (int j = 0; j < paramTypes.length; j++)
85. {
86. if (j > 0) System.out.print(", ");
87. System.out.print(paramTypes[j].getName());
88. }
89. System.out.println(");");
90. }
91. }
92.
93.
97. public static void printFields(Class cl)
98. {
99. Field[] fields = cl.getDeclaredFields();
100.
101. for (Field f : fields)
102. {
103. Class type = f.getType();
104. String name = f.getName();
105. System.out.print(" " + Modifier.toString(f.getModifiers()));
106. System.out.println(" " + type.getName() + " " + name + ";");
107. }
108. }
109. }
---------------------------------------
Using Reflection to Analyze Objects at Run Time
Example 5-6. ObjectAnalyzerTest.java
1. import java.lang.reflect.*;
2. import java.util.*;
3. import java.text.*;
4.
5. public class ObjectAnalyzerTest
6. {
7. public static void main(String[] args)
8. {
9. ArrayList squares = new ArrayList();
10. for (int i = 1; i <= 5; i++) squares.add(i * i);
11. System.out.println(new ObjectAnalyzer().toString(squares));
12. }
13. }
14.
15. class ObjectAnalyzer
16. {
17.
24. public String toString(Object obj)
25. {
26. if (obj == null) return "null";
27. if (visited.contains(obj)) return "...";
28. visited.add(obj);
29. Class cl = obj.getClass();
30. if (cl == String.class) return (String) obj;
31. if (cl.isArray())
32. {
33. String r = cl.getComponentType() + "[]{";
34. for (int i = 0; i < Array.getLength(obj); i++)
35. {
36. if (i > 0) r += ",";
37. Object val = Array.get(obj, i);
38. if (cl.getComponentType().isPrimitive()) r += val;
39. else r += toString(val);
40. }
41. return r + "}";
42. }
43.
44. String r = cl.getName();
45. // inspect the fields of this class and all superclasses
46. do
47. {
48. r += "[";
49. Field[] fields = cl.getDeclaredFields();
50. AccessibleObject.setAccessible(fields, true);
51. // get the names and values of all fields
52. for (Field f : fields)
53. {
54. if (!Modifier.isStatic(f.getModifiers()))
55. {
56. if (!r.endsWith("[")) r += ",";
57. r += f.getName() + "=";
58. try
59. {
60. Class t = f.getType();
61. Object val = f.get(obj);
62. if (t.isPrimitive()) r += val;
63. else r += toString(val);
64. }
65. catch (Exception e) { e.printStackTrace(); }
66. }
67. }
68. r += "]";
69. cl = cl.getSuperclass();
70. }
71. while (cl != null);
72.
73. return r;
74. }
75.
76. private ArrayList visited = new ArrayList();
77. }

----------------------------------------------------------------------
Using Reflection to Write Generic Array Code
a Java array remembers the type of its entries, that is, the element
type used in the new expression that created it. It is legal to cast
an Employee[] temporarily to an Object[] array and then cast it
back, but an array that started its life as an Object[] array can never
be cast into an Employee[] array. To write this kind of generic
array code, we need to be able to make a new array of the same
type as the original array. For this, we need the methods of the
Array class in the java.lang.reflect package. The key is the static
newInstance method of the Array class that constructs a new array.
You must supply the type for the entries and the desired length
as parameters to this method.
Example 5-7. ArrayGrowTest.java
1. import java.lang.reflect.*;
2. import java.util.*;
3.
4. public class ArrayGrowTest
5. {
6. public static void main(String[] args)
7. {
8. int[] a = { 1, 2, 3 };
9. a = (int[]) goodArrayGrow(a);
10. arrayPrint(a);
11.
12. String[] b = { "Tom", "Dick", "Harry" };
13. b = (String[]) goodArrayGrow(b);
14. arrayPrint(b);
15.
16. System.out.println("The following call will generate an exception.");
17. b = (String[]) badArrayGrow(b);
18. }
19.
20.
28. static Object[] badArrayGrow(Object[] a)
29. {
30. int newLength = a.length * 11 / 10 + 10;
31. Object[] newArray = new Object[newLength];
32. System.arraycopy(a, 0, newArray, 0, a.length);
33. return newArray;
34. }
35.
36.
44. static Object goodArrayGrow(Object a)
45. {
46. Class cl = a.getClass();
47. if (!cl.isArray()) return null;
48. Class componentType = cl.getComponentType();
49. int length = Array.getLength(a);
50. int newLength = length * 11 / 10 + 10;
51.
52. Object newArray = Array.newInstance(componentType, newLength);
53. System.arraycopy(a, 0, newArray, 0, length);
54. return newArray;
55. }
56.
57.
62. static void arrayPrint(Object a)
63. {
64. Class cl = a.getClass();
65. if (!cl.isArray()) return;
66. Class componentType = cl.getComponentType();
67. int length = Array.getLength(a);
68. System.out.print(componentType.getName()
69. + "[" + length + "] = { ");
70. for (int i = 0; i < Array.getLength(a); i++)
71. System.out.print(Array.get(a, i) + " ");
72. System.out.println("}");
73. }
74. }

---------------------------------------------------------------
Method Pointers!
On the surface, Java does not have method pointers—
ways of giving the location of a method to another
method so that the second method can invoke it later.
In fact, the designers of Java have said that method
pointers are dangerous and error prone and that Java
interfaces (discussed in the next chapter) are a superior
solution. However, it turns out that, as of JDK 1.1,
Java does have method pointers, as a
(perhaps accidental) by-product of the reflection package.
Example 5-8. MethodPointerTest.java
1. import java.lang.reflect.*;
2.
3. public class MethodPointerTest
4. {
5. public static void main(String[] args) throws Exception
6. {
7. // get method pointers to the square and sqrt methods
8. Method square = MethodPointerTest.class.getMethod("square",
9. double.class);
10. Method sqrt = Math.class.getMethod("sqrt", double.class);
11.
12. // print tables of x- and y-values
13.
14. printTable(1, 10, 10, square);
15. printTable(1, 10, 10, sqrt);
16. }
17.
18.
23. public static double square(double x)
24. {
25. return x * x;
26. }
27.
28.
36. public static void printTable(double from, double to,
37. int n, Method f)
38. {
39. // print out the method as table header
40. System.out.println(f);
41.
42. // construct formatter to print with 4 digits precision
43.
44. double dx = (to - from) / (n - 1);
45.
46. for (double x = from; x <= to; x += dx)
47. {
48. try
49. {
50. double y = (Double) f.invoke(null, x);
51. System.out.printf("%10.4f | %10.4f%n", x, y);
52. }
53. catch (Exception e) { e.printStackTrace(); }
54. }
55. }
56. }

免责声明:

① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。

② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341

java 又一摘要 Reflection

下载Word文档到电脑,方便收藏和打印~

下载Word文档

猜你喜欢

java 又一摘要 Reflection

Core java 一本很好的书[@more@]Only inner classes can be private.Regular classes always have either package or public visibilit
2023-06-03

Java实现MD5消息摘要算法

首先,必须要强调的一点,MD5不是加密算法,而是消息摘要算法,具有不可逆性。字符串通过MD5处理后会生成128位的二进制串。我们通常会将其转化为16进制串,用于登录密码验证。加密算法与消息摘要算法区别: 加密算法具有相应地解密算法,通过加
2023-05-31

怎么实现一个HmacMD5消息摘要算法

怎么实现一个HmacMD5消息摘要算法?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。算法实现:import javax.crypto.KeyGenerator; impor
2023-05-31

在DedeCMS中的文章页面的上一篇下一篇链接处增加文章摘要的方法

Dedecms系统默认的是在文章的上一篇和下一篇的链接只显示标题,但是有时我们希望显示其他信息,比如文章的摘要。找到arc.archives.class.php文件,在include目录下面,然后查找“GetPreNext&rd
2022-06-12

京东商城背后AI技术揭秘(一)——基于关键词自动生成摘要

导言过去几十年间,人类的计算能力获得了巨大提升;随着数据不断积累,算法日益先进,我们已经步入了人工智能时代。确实,人工智能概念很难理解,技术更是了不起,背后的数据和算法非常庞大复杂。很多人都在疑惑,现在或未来AI将会有哪些实际应用呢?其实,
2023-06-05

装ug一定要装java吗

安装ug一定要装java吗?安装ug本身是不需要装java的,但是安装ug8.5以上就需要安装java了。相关介绍:UG(Unigraphics NX)是Siemens PLM Software公司出品的一个产品工程解决方案,它为用户的产品设计及加工过程提供了
装ug一定要装java吗
2021-11-28

华为OD机试真题 Java 实现【字符串摘要】【2023 B卷 100分】,附详细解题思路

目录 一、题目描述 二、输入描述 三、输出描述 四、解题思路 1、核心思路: 2、具体思路如下: 五、Java算法源码 六、效果展示
2023-08-17

java培训时长一般需要多久

这篇文章主要介绍了java培训时长一般需要多久,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。一般来说,java培训时长大多在3-6个月,有一些基础的人是可以很快学会掌握jav
2023-06-20

学Java前一定要知道的4点是什么

本篇内容主要讲解“学Java前一定要知道的4点是什么”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“学Java前一定要知道的4点是什么”吧!一、Java是什么?作为一门面向对象编程语言。Java程
2023-06-16

编程热搜

  • Python 学习之路 - Python
    一、安装Python34Windows在Python官网(https://www.python.org/downloads/)下载安装包并安装。Python的默认安装路径是:C:\Python34配置环境变量:【右键计算机】--》【属性】-
    Python 学习之路 - Python
  • chatgpt的中文全称是什么
    chatgpt的中文全称是生成型预训练变换模型。ChatGPT是什么ChatGPT是美国人工智能研究实验室OpenAI开发的一种全新聊天机器人模型,它能够通过学习和理解人类的语言来进行对话,还能根据聊天的上下文进行互动,并协助人类完成一系列
    chatgpt的中文全称是什么
  • C/C++中extern函数使用详解
  • C/C++可变参数的使用
    可变参数的使用方法远远不止以下几种,不过在C,C++中使用可变参数时要小心,在使用printf()等函数时传入的参数个数一定不能比前面的格式化字符串中的’%’符号个数少,否则会产生访问越界,运气不好的话还会导致程序崩溃
    C/C++可变参数的使用
  • css样式文件该放在哪里
  • php中数组下标必须是连续的吗
  • Python 3 教程
    Python 3 教程 Python 的 3.0 版本,常被称为 Python 3000,或简称 Py3k。相对于 Python 的早期版本,这是一个较大的升级。为了不带入过多的累赘,Python 3.0 在设计的时候没有考虑向下兼容。 Python
    Python 3 教程
  • Python pip包管理
    一、前言    在Python中, 安装第三方模块是通过 setuptools 这个工具完成的。 Python有两个封装了 setuptools的包管理工具: easy_install  和  pip , 目前官方推荐使用 pip。    
    Python pip包管理
  • ubuntu如何重新编译内核
  • 改善Java代码之慎用java动态编译

目录