this.getClass().getResource详细讲解

本文通过一个具体的 Java TimerTask 示例,展示了如何使用 TimerTask 来执行定时任务,并演示了通过 getClass().getResource() 方法获取类路径的方法。
package com.wyl.cn;

import java.util.TimerTask;

public class TimerTest extends TimerTask {

	@Override
	public void run() {
		// TODO Auto-generated method stub
       System.out.println("测试TimerTask========》");
       String s1=this.getClass().getResource("").getPath();
       String s2=this.getClass().getResource("/").getPath();
       String s3=this.getClass().getResource("/com").getPath();
       String s4=this.getClass().getResource("/com/wyl").getPath();
       System.out.println(s1);
       System.out.println(s2);
       System.out.println(s3);
       System.out.println(s4);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		new TimerTest().run();

	}

}


<pre name="code" class="plain">测试TimerTask========》
/D:/plantix2.0_v1.0/PlantixStudio2.0/workspace1/tasktest/build/classes/com/wyl/cn/
/D:/plantix2.0_v1.0/PlantixStudio2.0/workspace1/tasktest/build/classes/
/D:/plantix2.0_v1.0/PlantixStudio2.0/workspace1/tasktest/build/classes/com
/D:/plantix2.0_v1.0/PlantixStudio2.0/workspace1/tasktest/build/classes/com/wyl




明白了,我们将对每一个概念进行详细讲解,并附上完整的示例代码,确保你能够理解每一个细节。以下是关于**多线程**、**Java反射**和**集合**的详细说明。 ### 多线程 #### 1. 创建线程的方式 ##### 1.1 继承 `Thread` 类 **详细实现方法** 当你继承 `Thread` 类时,你需要重写 `run()` 方法,这个方法包含了线程启动后要执行的代码。然后通过调用 `start()` 方法启动线程。 ```java class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } } } public class ThreadInheritanceExample { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); // 启动线程 } } ``` **关键点** - `run()` 方法包含线程的具体任务逻辑。 - 使用 `start()` 方法启动线程,不要直接调用 `run()`,否则不会创建新线程。 ##### 1.2 实现 `Runnable` 接口 **详细实现方法** 实现 `Runnable` 接口是一种更灵活的方式来创建线程。你可以将 `Runnable` 对象传递给 `Thread` 构造函数来启动线程。 ```java class MyRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + ": " + i); } } } public class RunnableInterfaceExample { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); // 启动线程 } } ``` **关键点** - `Runnable` 接口更适合任务与线程分离的设计模式。 - 可以让同一个 `Runnable` 实例由多个线程共享。 ##### 1.3 使用 `Callable` 和 `Future` **详细实现方法** `Callable` 接口允许线程完成任务后返回结果,并且可以抛出受检异常。`Future` 提供了获取结果、取消任务等功能。 ```java import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; class MyCallable implements Callable<Integer> { @Override public Integer call() throws Exception { int sum = 0; for (int i = 1; i <= 10; i++) { sum += i; } return sum; } } public class CallableFutureExample { public static void main(String[] args) { Callable<Integer> task = new MyCallable(); FutureTask<Integer> futureTask = new FutureTask<>(task); Thread thread = new Thread(futureTask); thread.start(); try { System.out.println("Sum: " + futureTask.get()); // 获取结果 } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } } ``` **关键点** - `Callable` 支持返回值和抛出异常。 - `Future` 提供对任务的异步控制能力。 #### 2. 线程同步 **详细实现方法** 为了避免多个线程同时访问共享资源时发生冲突,可以使用 `synchronized` 关键字。`synchronized` 方法或代码块确保同一时间只有一个线程可以执行。 ```java class Counter { private int count = 0; public synchronized void increment() { count++; } public synchronized int getCount() { return count; } } public class SynchronizationExample { public static void main(String[] args) { final Counter counter = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); Thread t2 = new Thread(() -> { for (int i = 0; i < 1000; i++) { counter.increment(); } }); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Final count: " + counter.getCount()); } } ``` **关键点** - `synchronized` 方法或代码块确保线程安全。 - `join()` 确保主线程等待子线程完成。 #### 3. 线程通信 **详细实现方法** 线程之间的通信可以通过 `wait()`、`notify()` 和 `notifyAll()` 方法实现。`wait()` 使当前线程进入等待状态,直到另一个线程调用 `notify()` 或 `notifyAll()` 唤醒它。 ```java class Resource { private boolean produced = false; public synchronized void produce() throws InterruptedException { if (produced) { wait(); // 等待消费 } System.out.println("Produced..."); produced = true; notify(); // 唤醒消费者 } public synchronized void consume() throws InterruptedException { if (!produced) { wait(); // 等待生产 } System.out.println("Consumed..."); produced = false; notify(); // 唤醒生产者 } } public class ThreadCommunicationExample { public static void main(String[] args) { final Resource resource = new Resource(); Thread producer = new Thread(() -> { try { while (true) { resource.produce(); Thread.sleep(1000); // 模拟生产间隔 } } catch (InterruptedException e) { e.printStackTrace(); } }); Thread consumer = new Thread(() -> { try { while (true) { resource.consume(); Thread.sleep(1000); // 模拟消费间隔 } } catch (InterruptedException e) { e.printStackTrace(); } }); producer.start(); consumer.start(); } } ``` **关键点** - `wait()` 使线程等待。 - `notify()` 唤醒单个等待线程。 - `notifyAll()` 唤醒所有等待线程。 --- ### Java反射 #### 1. 获取类信息 **详细实现方法** Java 反射允许你在运行时获取类的信息,包括构造函数、方法和字段。首先,你需要获得 `Class` 对象。 ```java import java.lang.reflect.Constructor; import java.lang.reflect.Method; public class ReflectionExample { public static void main(String[] args) throws Exception { // 获取Class对象 Class<?> clazz = Class.forName("java.util.ArrayList"); // 获取构造器 Constructor<?> constructor = clazz.getConstructor(); Object instance = constructor.newInstance(); // 获取方法并调用 Method addMethod = clazz.getMethod("add", Object.class); addMethod.invoke(instance, "Element"); // 打印列表内容 Method toStringMethod = clazz.getMethod("toString"); System.out.println(toStringMethod.invoke(instance)); } } ``` **关键点** - `Class.forName()` 返回指定类的 `Class` 对象。 - `getConstructor()` 和 `getMethod()` 分别获取构造器和方法。 - `invoke()` 调用方法。 #### 2. 访问私有成员 **详细实现方法** 你可以使用反射访问私有字段和方法。这通常用于测试或调试,但在生产环境中应谨慎使用。 ```java import java.lang.reflect.Field; public class PrivateFieldAccess { private String privateField = "Private Value"; public static void main(String[] args) throws Exception { Class<?> clazz = PrivateFieldAccess.class; Field field = clazz.getDeclaredField("privateField"); field.setAccessible(true); // 设置可访问私有字段 PrivateFieldAccess obj = new PrivateFieldAccess(); System.out.println(field.get(obj)); // 访问私有字段 } } ``` **关键点** - `getDeclaredField()` 获取私有字段。 - `setAccessible(true)` 允许访问私有成员。 #### 3. 动态代理 **详细实现方法** 动态代理允许你在运行时创建代理对象,拦截方法调用。这通常用于日志记录、权限检查等场景。 ```java import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; interface Service { void execute(); } class RealService implements Service { @Override public void execute() { System.out.println("Executing real service..."); } } class LoggingInvocationHandler implements InvocationHandler { private final Object target; public LoggingInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("Before method: " + method.getName()); Object result = method.invoke(target, args); System.out.println("After method: " + method.getName()); return result; } } public class DynamicProxyExample { public static void main(String[] args) { Service realService = new RealService(); InvocationHandler handler = new LoggingInvocationHandler(realService); Service proxyService = (Service) Proxy.newProxyInstance( realService.getClass().getClassLoader(), realService.getClass().getInterfaces(), handler ); proxyService.execute(); } } ``` **关键点** - `Proxy.newProxyInstance()` 创建代理对象。 - `InvocationHandler` 定义代理行为。 --- ### 集合 #### 1. List接口 **详细实现方法** `List` 是一个有序集合,允许重复元素。最常用的实现类是 `ArrayList`。 ```java import java.util.ArrayList; import java.util.List; public class ListExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Item 1"); list.add("Item 2"); list.add("Item 3"); for (String item : list) { System.out.println(item); } System.out.println("Index of 'Item 2': " + list.indexOf("Item 2")); System.out.println("Contains 'Item 3': " + list.contains("Item 3")); } } ``` **关键点** - `ArrayList` 适用于频繁的随机访问。 - `LinkedList` 更适合频繁的插入和删除操作。 #### 2. Set接口 **详细实现方法** `Set` 是一个不允许重复元素的集合。常用的实现类是 `HashSet`。 ```java import java.util.HashSet; import java.util.Set; public class SetExample { public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add("Item 1"); set.add("Item 2"); set.add("Item 2"); // 重复元素不会被添加 for (String item : set) { System.out.println(item); } System.out.println("Size: " + set.size()); System.out.println("Contains 'Item 2': " + set.contains("Item 2")); } } ``` **关键点** - `HashSet` 提供快速查找、插入和删除操作。 - `TreeSet` 提供排序功能。 #### 3. Map接口 **详细实现方法** `Map` 是键值对的集合,键唯一。常用的实现类是 `HashMap`。 ```java import java.util.HashMap; import java.util.Map; public class MapExample { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); map.put("Apple", 1); map.put("Banana", 2); for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } System.out.println("Value for 'Apple': " + map.get("Apple")); System.out.println("Contains key 'Banana': " + map.containsKey("Banana")); System.out.println("Contains value 2: " + map.containsValue(2)); } } ``` **关键点** - `HashMap` 提供快速查找、插入和删除操作。 - `TreeMap` 提供按键排序的功能。 --- 通过这些详细的例子和解释,希望你能更好地理解和应用多线程、Java反射和集合。如果你有任何疑问或需要更多示例,请随时提问!
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知乎关注八戒来了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值