new方法后面加大括号进行Override

本文介绍了一个使用Java匿名内部类覆盖父类方法的具体示例。通过该示例,可以了解如何利用匿名内部类来扩展已有类的功能,并观察到方法被成功重写后的输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class Car {
	public void run(){
		System.out.println("run");
	}

}

public class Test {
	
	
	public static void cartest(){
		
		Car car = new Car(){
			@Override
			public  void run(){
				System.out.println("run run!");
			}
		};
		
		car.run();
	}
	public static void main(String args[]){
		new Test().cartest();
	}

}
今天在阅读源码的时候发现了这个结构,感觉挺有意思,记录一下。
package BeiKe; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.*; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class CleanHouse { // 自定义InputFormat处理完整JSON数组 public static class WholeFileInputFormat extends FileInputFormat<Text, Text> { @Override public RecordReader<Text, Text> createRecordReader(InputSplit split, TaskAttemptContext context) { return new WholeFileRecordReader(); } @Override protected boolean isSplitable(JobContext context, Path file) { return false; // 禁止文件分割,确保整个JSON数组被完整读取 } } // 自定义RecordReader读取整个文件 public static class WholeFileRecordReader extends RecordReader<Text, Text> { private Text key = new Text(); private Text value = new Text(); private boolean processed = false; @Override public void initialize(InputSplit split, TaskAttemptContext context) throws IOException { FileSplit fileSplit = (FileSplit) split; Path path = fileSplit.getPath(); FileSystem fs = path.getFileSystem(context.getConfiguration()); try (FSDataInputStream in = fs.open(path); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } value.set(sb.toString()); } } @Override public boolean nextKeyValue() { if (!processed) { key.set("json_array"); processed = true; return true; } return false; } @Override public Text getCurrentKey() { return key; } @Override public Text getCurrentValue() { return value; } @Override public float getProgress() { return processed ? 1.0f : 0.0f; } @Override public void close() {} } // Mapper类处理JSON数组 public static class JsonMapper extends Mapper<Text, Text, Text, Text> { @Override protected void map(Text key, Text value, Context context) throws IOException, InterruptedException { try { String jsonString = value.toString().trim(); // 移除JSON数组前后的方括号(如果存在) if (jsonString.startsWith("[") && jsonString.endsWith("]")) { jsonString = jsonString.substring(1, jsonString.length() - 1); } // 分割JSON对象(假设对象之间用逗号分隔) String[] jsonObjects = jsonString.split(",(?=\\{)"); for (String obj : jsonObjects) { if (!obj.trim().isEmpty()) { JSONObject json = new JSONObject(obj.trim()); // 处理单价字段 String price = json.optString("单价(元/平方米)", ""); if (price.isEmpty() || "暂无信息".equals(price) || "无".equals(price)) { continue; } // 重命名字段 json.put("元/平方米", json.remove("单价(元/平方米)")); // 输出有效记录 context.write(new Text(json.getString("地点")), new Text(json.toString())); } } } catch (Exception e) { System.err.println("JSON处理错误: " + e.getMessage()); System.err.println("错误数据: " + value.toString()); } } } // Reducer类直接输出结果 public static class JsonReducer extends Reducer<Text, Text, Text, Text> { @Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { for (Text value : values) { context.write(null, value); } } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf, "JSON Array Processor"); job.setJarByClass(CleanHouse.class); job.setInputFormatClass(WholeFileInputFormat.class); job.setMapperClass(JsonMapper.class); job.setReducerClass(JsonReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true) ? 0 : 1); } }上述代码运行结果如下[root@hadoop01 software]# hadoop jar CleanHouse.jar /贝壳网南通地区房价数据.json /out 25/06/13 13:42:10 INFO client.RMProxy: Connecting to ResourceManager at hadoop01/192.168.164.128:8032 25/06/13 13:42:10 WARN mapreduce.JobResourceUploader: Hadoop command-line option parsing not performed. Implement the Tool interface and execute your application with ToolRunner to remedy this. 25/06/13 13:42:13 INFO input.FileInputFormat: Total input paths to process : 1 25/06/13 13:42:13 INFO mapreduce.JobSubmitter: number of splits:1 25/06/13 13:42:13 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1749776424019_0030 25/06/13 13:42:14 INFO impl.YarnClientImpl: Submitted application application_1749776424019_0030 25/06/13 13:42:14 INFO mapreduce.Job: The url to track the job: http://hadoop01:8088/proxy/application_1749776424019_0030/ 25/06/13 13:42:14 INFO mapreduce.Job: Running job: job_1749776424019_0030 25/06/13 13:42:27 INFO mapreduce.Job: Job job_1749776424019_0030 running in uber mode : false 25/06/13 13:42:27 INFO mapreduce.Job: map 0% reduce 0% 25/06/13 13:42:56 INFO mapreduce.Job: map 100% reduce 0% 25/06/13 13:43:13 INFO mapreduce.Job: map 100% reduce 100% 25/06/13 13:43:14 INFO mapreduce.Job: Job job_1749776424019_0030 completed successfully 25/06/13 13:43:14 INFO mapreduce.Job: Counters: 49 File System Counters FILE: Number of bytes read=203 FILE: Number of bytes written=283483 FILE: Number of read operations=0 FILE: Number of large read operations=0 FILE: Number of write operations=0 HDFS: Number of bytes read=475889 HDFS: Number of bytes written=153 HDFS: Number of read operations=6 HDFS: Number of large read operations=0 HDFS: Number of write operations=2 Job Counters Launched map tasks=1 Launched reduce tasks=1 Data-local map tasks=1 Total time spent by all maps in occupied slots (ms)=25723 Total time spent by all reduces in occupied slots (ms)=12371 Total time spent by all map tasks (ms)=25723 Total time spent by all reduce tasks (ms)=12371 Total vcore-milliseconds taken by all map tasks=25723 Total vcore-milliseconds taken by all reduce tasks=12371 Total megabyte-milliseconds taken by all map tasks=26340352 Total megabyte-milliseconds taken by all reduce tasks=12667904 Map-Reduce Framework Map input records=1 Map output records=1 Map output bytes=194 Map output materialized bytes=203 Input split bytes=124 Combine input records=0 Combine output records=0 Reduce input groups=1 Reduce shuffle bytes=203 Reduce input records=1 Reduce output records=1 Spilled Records=2 Shuffled Maps =1 Failed Shuffles=0 Merged Map outputs=1 GC time elapsed (ms)=497 CPU time spent (ms)=3640 Physical memory (bytes) snapshot=433668096 Virtual memory (bytes) snapshot=4200083456 Total committed heap usage (bytes)=274726912 Shuffle Errors BAD_ID=0 CONNECTION=0 IO_ERROR=0 WRONG_LENGTH=0 WRONG_MAP=0 WRONG_REDUCE=0 File Input Format Counters Bytes Read=475765 File Output Format Counters Bytes Written=153 [root@hadoop01 software]# hadoop fs -cat /out/part* {“地点”:“(苏锡通园区) 江海路蓝天花苑”,“元/平方米”:“4867元/平方米”,“绿化率”:0.2,“开发商”:“无”,“建成年代”:“1998-2010年”} ,但json中有有多条数据,且要求输出格式与下面类似{ "地点": "(海门区) 通源路147号", "单价(元/平方米)": "9281元/平方米", "绿化率": 0.35, "开发商": "暂无信息", "建成年代": "2001-2015年" }, { "地点": "(海门区) 丝绸东路299号", "单价(元/平方米)": "7716元/平方米", "绿化率": 0.3, "开发商": "沪商置业有限公司", "建成年代": "2013-2020年" }, { "地点": "(海门区) 粉坊弄", "单价(元/平方米)": "8178元/平方米", "绿化率": 0.01, "开发商": "上海中海海昆房地产有限公司", "建成年代": "1993-2008年" }
06-14
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值